Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms: Close modal dialog when clicking outside the dialog

Tags:

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?

like image 940
Kottan Avatar asked Dec 22 '10 08:12

Kottan


2 Answers

You should change it to a non-modal dialog (open it with Show(..)) and then use the Deactivate event and close it.

like image 123
Elmex Avatar answered Dec 01 '22 00:12

Elmex


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

like image 33
pogojotz Avatar answered Dec 01 '22 01:12

pogojotz