AfxMessageBox with Auto-close


This article describes how to make the MFC function AfxMessageBox to dispay a message box that is automatically dismissed after a given time.
Auto-close message box

For that purpose we can do the following:

  1. Override CWinApp::DoMessageBox virtual function for customzing the default AfxMessageBox.
  2. Set a CBT hook to catch the message box creation.
  3. In the CBT hook procedure, subclass the message box window procedure.
  4. In the message box procedure, handle WM_INITDIALOG message and set a timer.
  5. Handle WM_TIMER to automatically close the message box.

Next are simplified code snippets that show how to implement the steps described above. CAutoMessageBox is a class designed to implement the message box with auto-close (sets CBT hook, subclasses the message box and so on).
More detailed code can be found in the demo application attached at the end of the article.

1. Override CWinApp::DoMessageBox

2. Set the CBT hook

3. Subclass the message box window procedure

4. Handle WM_INITDIALOG and set a timer

5. Handle WM_TIMER and close the message box

Demo application

You can find attached here a simple dialog-based application for demo purpose.


Just choose the options (time out, message box style and so on) then click “Say Hello!” button. If “Auto close” is checked, a message box with time-out will be shown.


See also


4 thoughts on “AfxMessageBox with Auto-close

  1. vaibhav mathur

    Hi Ovidiu
    is there a way by which we could change the time out message,
    i.e. the lapse value of timer..e.g we have set the timer of 10 sec so the text of message would get changed as 10,9,8,7 ,6 and so on.

    1. Ovidiu Cucu Post author

      First, thank you for the feedback!
      Indeed, would be a good idea to display a text that shows the time left. I will post asap a new article, completing this one.
      Just keep in touch! 😉


Leave a Reply