showdialog 从另一个线程关闭
showdialog closing from another thread
我的主线程中有一个 ShowDialog(),我试图从另一个正在等待外部设备输入(COM 端口)的线程中关闭它。为此,我将主线程的 DialogResult 设置为 DialogResult.OK。问题是 showdialog window 保持打开状态,直到我(以编程方式或手动方式)将鼠标移到我的应用程序上。这很好,但是很脏。是否有更简洁的关闭 ShowDialog 的方法?
我的 code/things 我试过:
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();
});
我的主线程中有一个 ShowDialog(),我试图从另一个正在等待外部设备输入(COM 端口)的线程中关闭它。为此,我将主线程的 DialogResult 设置为 DialogResult.OK。问题是 showdialog window 保持打开状态,直到我(以编程方式或手动方式)将鼠标移到我的应用程序上。这很好,但是很脏。是否有更简洁的关闭 ShowDialog 的方法?
我的 code/things 我试过:
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();
});