showdialog从另一个线程关闭

时间:2015-08-10 12:56:54

标签: c# .net c#-3.0

我的主线程中有一个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); 

1 个答案:

答案 0 :(得分:1)

我想我找到了解决方案。

我删除了所有的DialogResult内容,并将其替换为:

_prompt.Invoke((MethodInvoker)delegate
{
    _prompt.Close();
});