gpt4 book ai didi

c# - 新窗体上的 STAThread 错误(SaveFileDialog)

转载 作者:太空宇宙 更新时间:2023-11-03 16:09:19 26 4
gpt4 key购买 nike

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

{"Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process."} In this code

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
}

这是我的 Program.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());
}

最佳答案

如果您从第二个线程中调用 FSave.ShowDialog(),您将收到此错误。您应该始终从主应用程序线程中打开 Windows 窗体。

考虑调用委托(delegate)来显示您的线程中的对话,而不是直接打开表单。

关于c# - 新窗体上的 STAThread 错误(SaveFileDialog),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18093272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com