Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Form and using Form.ShowDialog on a background thread

Using Winforms, If I'm on a thread that is not the "main" ui thread can I safetly

  1. Create a Form,
  2. Call ShowDialog on that form

It seems like I would be obeying the rule of: Winforms controls must be modified on the thread they were created in.

From some of the reading I've done it seems like ShowDialog will create its own message pump so that I don't need to worry about the Form being created on a thread that already has a message pump.

The background of the question is that I get a callback where I'd like to display some Winforms UI, but I don't have access to any other UI that I could use to Invoke to the main thread.

like image 245
Matt Smith Avatar asked Jun 05 '12 22:06

Matt Smith


2 Answers

That's roughly correct, albeit that it is pretty important that you call the thread's SetApartmentState() method to switch the thread to STA. Important for many UI operations, including the clipboard, drag and drop and the shell dialogs. And that you usually have a crummy Z-order problem when the form that you create on the thread is not in the foreground and hides behind another window. Or has the nasty habit of actually do move in the foreground when the user doesn't expect it and grab a mouse click or keystroke unexpectedly.

These are hard problems to fix, they do make your app flaky. There's no good reason to not have a reference to invoke to, you can also pass it to the class some way some how. You've always got Application.OpenForms[0] to fall back on, if really necessary.

like image 128
Hans Passant Avatar answered Nov 17 '22 01:11

Hans Passant


Yes, you can do that, but if you want the dialog to actually act like a modal dialog (i.e., block the parent Window, which I assume you want since you are calling ShowDialog) then be prepared to be disappointed.

What problem are you actually trying to solve here. It sounds like you want a modal dialog that doesn't block, which is a bit strange. If you explain the problem at hand there may exist a solution you have not yet considered.

like image 43
Ed S. Avatar answered Nov 17 '22 02:11

Ed S.