【问题标题】:My form is not opening in STA我的表格没有在 STA 中打开
【发布时间】:2013-12-23 17:29:27
【问题描述】:

我正在尝试从我的登录表单打开我的主表单。

Application.Run(new Form1(usernameText.Text));

但它没有在 STA 中打开。所以我的主窗体中的 folderBrowserDialog1 不会打开。我在我的 program.cs 中有 [STAThread] 就在 static void Main() 上方,但它仍然无法正常工作......所以我不知道该怎么办......

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new loginForm());
}

【问题讨论】:

  • 有什么问题?会发生什么?
  • 我不是很肯定,但我认为两次调用Application.Run() 是一件坏事。不确定这是否会导致您的问题。如果是这样,您可以使用Form.Show(),并使用Application.Run() 的无参数版本(只需确保在主窗体关闭时使用Application.Exit())。
  • @SLaks 发生这种情况:当前线程必须设置为单线程单元 (STA) 模式,然后才能进行 OLE 调用。确保您的 Main 函数上标记了 STAThreadAttribute。仅当将调试器附加到进程时才会引发此异常。
  • 在最后一个问题中使用my answer,而不是您接受的问题。您现在正在运行两个消息循环,一个在另一个内部。那是……通常要避免的事情。
  • 您的代码在哪里运行?调用堆栈是什么?

标签: c# multithreading winforms


【解决方案1】:

这是 Servy 对您的 similar question 的回复:

转到您的 program.cs 文件并对其进行更改,以便显示您的登录表单。然后,在它关闭后,确定是否应该打开另一个表单。

它可能看起来像这样:

LoginForm loginform = new LoginForm();
Application.Run(loginform);

if (loginform.DialogResult == DialogResult.Yes)
    Application.Run(new MainForm());
//TODO handle error cases

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 2020-12-13
    • 1970-01-01
    相关资源
    最近更新 更多