Scott Miller
Scott Miller

Reputation: 447

Multiple messageboxes with the same owner

I have an app that responds to external events (generated outside of the application) by showing a messagebox (MessageBox.Show). It sets the owner to my app's main window.

If a second event comes in before the first modal is dismissed, I end up with two messageboxes. The problem comes when I dismiss the first model messagebox before the second. In this case, the second box stays visible, but it has lost its "modal-ness" - I can operate the app as if this second modal window is not there.

One solution I have tried is to remove the owner parameter from the MessageBox.Show call. According to these docs: "By default, the message box appears in front of the window that is currently active." I figure by not specifying an owner, the "active" window will be the owner. If there is no modal, then the main window is active. If there is a modal already that one will be active and as the owner, the messageboxes will be "stacked" and I won't be able to dismiss them out of order.

Unfortunately, this did not work. None of the modals had an owner - even the first messagebox was not modal and did not block the main window.

I considered saving each messagebox's window and using that as the owner of the next, but then I realized there is no direct way to get the window handle of a messagebox - the Show() method generates the window, and that does not return until the box is dismissed.

My question is in two parts: Is this the expected behavior from messageboxes? And, what can / should I be doing to avoid a situation where a non-modal messagebox is open in my application?

Upvotes: 0

Views: 134

Answers (1)

Mike Strobel
Mike Strobel

Reputation: 25623

One solution would be to place the external events in a queue, and show only one MessageBox at a time. When one is closed, process the next event in the queue, if one exists. That way, only one shows at a time, so one MessageBox cannot be owned by another, and they should each be owned by whichever application window is active at the time it is displayed. And, because you're using a queue, they will appear in the same order that the underlying events were received.

Upvotes: 1

Related Questions