Auto-close message box

文章来源:http://www.codeproject.com/Articles/19714/Auto-close-message-box

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_CLOSEmessage to close the message box. That's it !

void CMsgBox::MessageBox(CString sMsg, CString sCaption, UINT nSleep, 
                         UINT nFlags, bool bAutoClose)
{
    // Save the caption, for finding this 
    // message box window later

    m_Caption = sCaption;  

    // If auto close then, start the timer.

    if(bAutoClose)
        SetTimer(100, nSleep, NULL);

    // Show the message box

    CWnd::MessageBox(sMsg, sCaption, nFlags);
}

void CMsgBox::OnTimer(UINT nIDEvent) 
{
    // TODO: Add your message handler code here and/or call default

    BOOL bRetVal = false;

    // Find the message box window using the caption

    CWnd* pWnd = FindWindow(NULL, m_Caption);
    if(pWnd != NULL)
    {
        // Send close command to the message box window

        ::PostMessage(pWnd->m_hWnd, WM_CLOSE, 0, 0);
    }

    // Kill the timer

    KillTimer(100);

    CWnd::OnTimer(nIDEvent);
}

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:

CMsgBox obj(this);

Or like this:

CMsgBox obj;
obj.SetParent(this);

Use the 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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值