自动关闭MessageBox
BY thammadi
介绍
我曾看到许多这样的文章,但是都比较复杂,因此我就想我要写一个简单的一点的一个。


理解CMsgBox 类
CMsgBox是一个实现了自动关闭功能的类。这个类从CWnd类继承。 它提供了一个叫做“MessageBox()”的方法,反过来这个方法调用CWnd::MessageBox()来显示消息对话框。
获得自动关闭的功能非常简单,在CMsgBox::MessageBox()方法中,调用CWnd::MessageBox API之前,我们开启一个定时器(SetTimer()方法)。在OnTimer方法中,我们尝试通过使用窗口名字(caption)查找MessageBox窗口。一旦找到,我们发送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);
结 论
那很简单不是吗!这也是我第一次投递,请原谅我的错误。
参 考
delaymessagebox by Nishant Shivkumar