Winforms: Close modal dialog when clicking outside the dialog

后端 未结 5 1320
旧巷少年郎
旧巷少年郎 2020-12-17 10:08

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?

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 11:00

    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

提交回复
热议问题