新表单上的STAThread错误(SaveFileDialog)

本文关键字:STAThread 错误 SaveFileDialog 表单 新表单 | 更新日期: 2023-09-27 18:26:37

所以基本上我已经为我的程序创建了一个登录系统,当用户登录时,它会打开Form1。但我需要Form1成为STA线程。我在Form1:中收到此错误

{"在进行OLE调用之前,必须将当前线程设置为单线程单元(STA)模式。请确保Main函数上标记了STAThreadAttribute。只有当调试器附加到进程时,才会引发此异常。"}在这个代码

SaveFileDialog FSave = new SaveFileDialog()
        {
            Filter = "Executable Files|*.exe",
            InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
        };
        if (FSave.ShowDialog() == DialogResult.OK)//im getting the error here
        {
        // CodeDom compiler code
        }

这是我的程序.cs

using System;
using System.Windows.Forms;
namespace hwid_login_system
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Login());
        }
    }
}

这就是我在表单登录中打开表单Form1的方式

private void complete()
    {
        if (loggedin && hwid)
        {
            MessageBox.Show("Logged in successfully!");
            System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
            t.Start();
            this.Close();
        }
        else
            MessageBox.Show("Something else went wrong..", "Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
public static void ThreadProc()
    {
        Application.Run(new Form1());
    }

新表单上的STAThread错误(SaveFileDialog)

如果在第二个线程中调用FSave.ShowDialog(),则会出现此错误。您应该始终从主应用程序线程中打开windows窗体。

请考虑从线程调用委托来显示对话框,而不是直接打开表单。