65.9K
CodeProject 正在变化。 阅读更多。
Home

自动关闭消息框

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.47/5 (10投票s)

2007 年 7 月 24 日

CPOL

1分钟阅读

viewsIcon

177477

downloadIcon

7492

一个自动关闭消息框的简单解决方案。

Screenshot - Image1.jpg

Screenshot - Image2.jpg

引言

本文描述了一个自动关闭消息框的简单解决方案。我查看了互联网上许多类似的的文章,它们都相当复杂,所以我认为可以使这个更简单一些。

理解 CMsgBox 类

CMsgBox 是一个实现自动关闭功能的类。该类是从 CWnd 类派生的。它暴露了一个名为“MessageBox()”的方法,该方法反过来会调用 CWnd::MessageBox() 来显示消息框。

实现自动关闭功能非常简单。在 CMsgBox::MessageBox() 方法中,我们在调用 CWnd::MessageBox API 之前启动一个计时器(SetTimer() 方法)。在 OnTimer 方法中,我们尝试使用其窗口名称(标题)找到消息框窗口。找到后,我们发布一个 WM_CLOSE 消息来关闭消息框。就完成了!

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);
}

使用代码

将这两个文件添加到您的项目中:“MsgBox.cpp”和“MsgBox.h”。在适当的地方#include "MsgBox.h"。创建 CMsgBox 对象如下:

CMsgBox obj(this);

或者像这样:

CMsgBox obj;
obj.SetParent(this);

使用 MessageBox() 方法显示消息框。如果不需要自动关闭功能,请将 bAutoClose 参数设置为 false。

obj.MessageBox("This message box will auto close in 2 seconds.", 
               "Auto Close Msg Box", 2000, MB_OK | MB_ICONINFORMATION);

结论

是不是很简单?另外,由于这是我的第一篇帖子,请原谅我可能犯的任何错误。

参考文献

© . All rights reserved.