[英]showdialog closing from another thread
我的主线程中有一个ShowDialog(),并且试图从另一个正在等待外部设备输入(COM端口)的线程中将其关闭。 我将主线程的DialogResult设置为DialogResult.OK。 问题是showdialog窗口保持打开状态,直到我(以编程方式或手动方式)将鼠标移到我的应用程序上。 很好,但是很脏。 有没有一种更清洁的方法来关闭ShowDialog?
我尝试过的代码/内容:
public Form _prompt;
..in my main thread
_prompt = new Form();
..add layout
_prompt.ShowDialog();
Console.WriteLine("closed!"); //doesnt print until mouse is moved
..side thread
Console.WriteLine("close it!"); //prints at the correct time
_prompt.DialogResult = DialogResult.OK; //this is what causes all the weirdness, it will make the form close but only after it is updated.
//doesn't fix it, instead throws System.InvalidOperationException: not allowed to do this from another thread
_prompt.Close();
//same as Close()
_prompt.Focus();
//same as the above
_prompt.Hide();
//does absolutely nothing
Application.DoEvents();
//works, but only if the cursor already is ontop of one of the forms
Cursor.Position = Cursor.Position;
//dirty hack, works, but I want to avoid this and instead have a cleaner solution
Rectangle screenRect = Screen.GetBounds(Bounds);
Cursor.Position = new Point(screenRect.Width / 2, screenRect.Height / 2);
我想我找到了解决方案。
我删除了所有DialogResult内容,并替换为:
_prompt.Invoke((MethodInvoker)delegate
{
_prompt.Close();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.