问题描述
从没有窗口 (ProcessWindowStyle.Hidden
) 的控制台应用程序中,我需要启动并显示一个表单(是的 - 我知道这是应该避免的糟糕设计)。
var thread = new Thread(() =>
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyCustomMessageBoxForm());
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = false;
thread.Start();
thread.Join();
这不起作用:表单将被创建,但被隐藏。您需要手动将 Visible
设置为 true
以使其按预期工作(请参阅 Show Form from hidden console application 的回答)。
var thread = new Thread(() =>
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyCustomMessageBoxForm { Visible = true }); //Note the change
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = false;
thread.Start();
thread.Join();
答案和我都没有解释为什么您必须明确设置可见性 - 在“普通”控制台应用程序(带有可见的控制台窗口)中,这不需要。
无论如何,让我更困惑的是,在调用 MessageBox.Show 之后,不再需要这个显式集来使其工作 - 更重要的是,在应用程序中调用 MessageBox.Show 的位置并不重要(是否相同线程与否),因此下面的两个示例都按预期工作:
MessageBox.Show("test"); // Note: called on other thread
var thread = new Thread(() =>
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyCustomMessageBoxForm()); //Works
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = false;
thread.Start();
thread.Join();
和
var thread = new Thread(() =>
{
MessageBox.Show("test"); //Note: called on same thread
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyCustomMessageBoxForm()); //Works
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = false;
thread.Start();
thread.Join();
所以我的问题是:为什么会发生这种情况 - 调用 MessageBox.Show 涉及什么(跨线程!)副作用?
注意:我使用了 .NET Framework,.NET Core 或 .NET 5 的行为可能会有所不同。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)