Modal dialogs can only block messages from the mouse, keyboard, and other messages, and modal dialogs will monopolize user input. The implementation principle is as follows:
- Let the parent window fail EnableWindow (Pardent,false);
- Create modal dialog box own message loop
- Until a shutdown message is received, the message loop terminates and the window is destroyed
Among the EnableWindow functions are:
Enables or disables mouse and keyboard input to the specified window or control. When input was disabled, the window does not receive input such as mouse clicks and key presses. When input was enabled, the window receives all input.
You can see that EnableWindow controls whether to receive messages from the keyboard or mouse.
A typical message loop in a Windows program is:
while 0 0 ) >0) { translatemessage (&msg); DispatchMessage (&msg);
The main window itself has a message loop, and when a modal dialog box is created, the program enters the modal dialog's message loop until it exits, then executes the message loop of the main window. There is only one message queue in a thread, but there may be other local message loops outside the main thread message loop, but they will not execute in parallel. So the message that the application sends can still be assigned to the specified window through the modal dialog message loop. For a modeless dialog box, there is no effect on the message of the main window because it has a message loop with the main window.
The relationship between the main message loop and the local message loop in the modal dialog box is as follows
Here is a test using the MessageBox (the MessageBox is modal dialog), testing the response to the timer (Wm_timer message) after the main window pops up the MessageBox. To draw the main window in OnTimer:
void Cmodalandmessagedlg::ontimer (uint_ptr nidevent) { // TODO: Add the message Handler code here and/or call the default value cclientdc DC (this); CRect rect; GetClientRect (&rect); dc. Fillsolidrect (Rect,rgb (rand ()%255, rand ()%255, rand ()%255));}
Button response on main window:
void Cmodalandmessagedlg::onbnclickedok () { // TODO: Add control notification handler code here SetTimer (1 ,+, NULL); MessageBox (L"hello! " );}
The test can find that the color of the pop-up MessageBox is still changing, which means that the message loop of the WM_TIMER message still relies on the non-modal dialog box is assigned to the main window.
SOURCE download
modal dialog box test