I have an open modal dialog (Windows Forms). I want, that the dialog is closed when clicking outside the dialog (on the parent form). How can I do that?
You should change it to a non-modal dialog (open it with Show(..)
) and then use the Deactivate
event and close it.
There are reasons (e.g. framework workarounds etc.) which force one to use a modal dialog. You can emulate the Deactivate
event by overriding the form method WndProc
like this:
protected override void WndProc(ref Message m) { const UInt32 WM_NCACTIVATE = 0x0086; if (m.Msg == WM_NCACTIVATE && m.WParam.ToInt32() == 0) { handleDeactivate(); } else { base.WndProc(ref m); } }
The WM_NCACTIVATE
message is send to tell the form to indicate whether it is active (WParam == 1
) or inactive (WParam == 0
). If you click somewhere on the parent form your modal dialog begins to "blink with activity" telling you, that it is more important right now. This is achieved by sending the previously mentioned Messages a few times (deactivate -> activate -> deactivate -> ... -> activate).
But be careful, if the handleDeactivate()
method is not terminating your form, it will be called every time the deactivate messages come. You have to handle that yourself.
Links:
MSDN Forum
MSDN Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With