SendMessage/PostMessage WM_CLOSE to MessageBox window does not always work

Hello -

I am running into a problem closing a MessageBox window using SendMessage (or PostMessage) with WM_CLOSE. In my app I have created a MessageBox with a timeout - based on sample code from CodeProject. When my MessageBox has a single OK button only, my timer closes the window fine. But, in the case where my MessageBox has Yes/No buttons, the close code in the timer is not working. I know that I have the correct window handle, as I call SetWindowText to demonstrate this fact. Everywhere I look, it says to close any window by passing it WM_CLOSE message. I have tried calling DestroyWindow, but that does not work. Any help would be appreciated.

Here is my code that calls my timed messagebox:

if (g_initiate_restart == TENTATIVE_RESTART) // Service restart tentative?
{
// Ask user whether or not to restart now
retval = m_MsgBox.MessageBox(GS(IDS_FORCE_RST_MSG),"Service Restart Warning", 15000, MB_YESNO | MB_ICONWARNING, TRUE);
if (retval == IDYES)
{
g_restart_msg_resp = RESP_IS_YES; // Set global restart-response flag to YES value
}
else if (retval == IDNO)
{
g_restart_msg_resp = RESP_IS_NO; // Set global restart-response flag to NO value
}
}
if (g_initiate_restart == FORCE_RESTART) // Forced service restart?
{
retval = m_MsgBox.MessageBox(GS(IDS_FORCE_RST_MSG),"Service Restart Warning", 15000, MB_OK | MB_ICONWARNING, TRUE);
g_restart_msg_resp = RESP_IS_YES; // Set global restart-response flag to YES value
}

===================================

Here is code from my new class CTimedMsgBox:

void CTimedMsgBox::OnTimer(UINT nIDEvent)
{

BOOL bRetVal = false;

// Find the message box window
CWnd* pWnd = FindWindow(NULL, m_Caption);
if(pWnd != NULL)
{
// Send close command to the message box window
::SetWindowText(pWnd->m_hWnd, _T("GOT ME"));
Sleep(3000);
::PostMessage(pWnd->m_hWnd, WM_CLOSE, 0, 0);
Sleep(2);
g_restart_msg_resp = RESP_IS_YES; // set user response to YES
}

// Kill the timer
KillTimer(100);

CWnd::OnTimer(nIDEvent);

}

int CTimedMsgBox::MessageBox(CString sMsg, CString sCaption, UINT nSleep, UINT nFlags, bool bAutoClose)
{
// Save the caption, for finding this
// message box window later
m_Caption = sCaption;
int retval;

// If auto close selected then, start the timer.
if(bAutoClose)
SetTimer(100, nSleep, NULL);

// Show the message box
retval = CWnd::MessageBox(sMsg, sCaption, nFlags);
return retval;
}






--------------------------------------------------------------------------------
Michael G. Rose -Unisys Corporation
Well.....that did the trick. Using MB_OKCANCEL instead of MB_YESNO somehow allows the ::PostMessage(pWnd->m_hWnd, WM_CLOSE, 0, 0); to close the window. Since this is a simple 2-flavor pop-up, I am going to use this.

Topic archived. No new replies allowed.