This article describes a simple solution for automatically closing a message box. I have looked at many similar articles in the Inetrnet which are quite complex, so I thought I would make this one a little more simple.
Understanding the CMsgBox class
CMsgBox is a class which implements auto-close functionality. This class is derived from the
CWnd class. It exposes a method called "
MessageBox()", which in turn would call
CWnd::MessageBox() to display a message box.
Getting the auto-close functionality implemented is very simple. In the
CMsgBox::MessageBox() method, we start a timer (
SetTimer() method) just before we call the
CWnd::MessageBox API. In the
OnTimer method, we try to find the message box window by using its window name (caption). Once found, we post a
WM_CLOSE message to close the message box. That's it !
void CMsgBox::MessageBox(CString sMsg, CString sCaption, UINT nSleep,
UINT nFlags, bool bAutoClose)
m_Caption = sCaption;
SetTimer(100, nSleep, NULL);
CWnd::MessageBox(sMsg, sCaption, nFlags);
void CMsgBox::OnTimer(UINT nIDEvent)
BOOL bRetVal = false;
CWnd* pWnd = FindWindow(NULL, m_Caption);
if(pWnd != NULL)
::PostMessage(pWnd->m_hWnd, WM_CLOSE, 0, 0);
Using the code
Add these two files to your project: "MsgBox.cpp" and "MsgBox.h".
#include "MsgBox.h" wherever appropriate. Create the
CMsgBox object as:
Or like this:
MessageBox() method for displaying the message box. Set the
bAutoClose parameter to false if you don't need the auto-close functionality.
obj.MessageBox("This message box will auto close in 2 seconds.",
"Auto Close Msg Box", 2000, MB_OK | MB_ICONINFORMATION);
Wasn't that simple? Also, this being my first post, please forgive me for any mistakes.
Sandeep completed his masters in Computer Applications in 2003 and has been hooked onto programming since then. His first project involved communicating with hardware devices which actually got him more interested in device programming.