L0laapk3
L0laapk3

Reputation: 958

showdialog closing from another thread

I have a ShowDialog() in my main thread, and I'm trying to close it from another thread that is waiting for an external device input (COM port). I do this by setting the DialogResult of my main thread to DialogResult.OK. The problem is that the showdialog window stays open until I (programmaticly or manually) move the mouse over my application. This is fine, but its dirty. Is there a cleaner way of closing the ShowDialog?

my code/things I've tried:

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); 

Upvotes: 0

Views: 1874

Answers (1)

L0laapk3
L0laapk3

Reputation: 958

I think I found the solution.

I removed all the DialogResult stuff, and replaced it with:

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

Upvotes: 3

Related Questions