Monday, April 14, 2008

MessageBox in ExitInstance

Like the problem in displaying the message box in InitInstance of an APP class, there is a problem in displaying the message box in ExitInstance() also. Try the following code..

int CMyApp::ExitInstance()
{
AfxMessageBox( "Some message from CMyApp::ExitInstance" );
return CWinApp::ExitInstance();
}

The messagebox will never appear!!!! After a small investigation, I found that this is beacuse of the WM_QUIT message that exists in the message queue. So removing the WM_QUIT message from the message queue will simply solve the problem. For removing the WM_QUIT, a GetMessage() function in while loop while be enough. So I modified the code as follows..

int CMyApp::ExitInstance()
{
MSG stMsg;
while( GetMessage( &stMsg,0,0,0));
AfxMessageBox( "Some message from CMyApp::ExitInstance" );
return CWinApp::ExitInstance();
}

After this the message box is showing correctly. The Theory is that, when we try to create a window and at that time if a WM_QUIT message exists in the message queue, the window creation will fail. Putting the GetMessage in the while loop will remove the WM_QUIT from the message loop also GetMessage will return false if it encounters a WM_QUIT. Thus it exits from the while loop.

Though we got a soltion, did you thought who send the WM_QUIT message? The WM_QUIT message is normally created using the PostQuitMessage() and in MFC AfxPostQuitMessage() function wrappers PostQuitMessage(). So I put a breakpoint in AfxPostQuitMessage() and waited. Upon clicking the Close button in the dialog, the break point triggered. And the callstack window shows that the CWnd::OnNcDestroy() function called AfxPostQuitMessage().

If you check the CWnd::OnNcDestroy() function, you can find that, it calls the AfxPostQuitMessage upon checking various conditions such as The window closed now is a Main Window, The Current instance is not a dll etc..

No comments:

Post a Comment