日期:2014-05-19  浏览次数:20918 次

请问有没有办法让messagebox对话框自动销毁?
程序在启动的时候有个messagebox.show弹出的对话框,如果不点确定,程序就无法继续下去。现在想设置一个时间,比如10秒,如果10秒后还没有人点确定,则对话框自己返回确定,并自己销毁。有办法么?

------解决方案--------------------
昨天刚好在CodeProject上看到一个这样的解决办法,不过是用MFC写的,代码如下:
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);
}
大概原理是在程序里设置一个计时器,弹出MessageBox前开始计时,当计时器到点以后,用FindWindow找到MessageBox的句柄,然后向这个窗口发送一个WM_CLOSE消息。

http://www.codeproject.com/useritems/AutoCloseMessageBox.asp
------解决方案--------------------
C# 代码,如果要测试,则新建一个Winform项目.然后在窗口里添加一个按钮.并将此按钮的Click事件指向Button_Click方法即可.

代码如下:

private void Button_Click(object sender, System.EventArgs e)
{
StartKiller();
MessageBox.Show( "这里是MessageBox弹出的内容 ", "MessageBox ");
MessageBox.Show( "这里是跟随运行的窗口 ", "窗口 ");
}

private void StartKiller()
{
Timer timer = new Timer();
timer.Interval = 10000; //10秒启动
timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{
KillMessageBox();
//停止计时器
((Timer)sender).Stop();
}

private void KillMessageBox()
{
//查找MessageBox的弹出窗口,注意对应标题
IntPtr ptr = FindWindow(null, "MessageBox ");
if(ptr != IntPtr.Zero)
{
//查找到窗口则关闭
PostMessage(ptr,WM_CLOSE,IntPtr.Zero,IntPtr.Zero);
}
}

[DllImport( "user32.dll ", EntryPoint = "FindWindow ", CharSet=CharSet.Auto)]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport( "user32.dll ", CharSet=CharSet.Auto)]
public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

public const int WM_CLOSE = 0x10;