C# 中 MessageBox 定时关闭
WPF中 System.Windows.Forms 的 MessageBox 并未提供定时关闭的功能,所以要实现此目标,需添加一些其他代码,如定时监控等。
需求说明:
- 弹出提示框后若一定时间内未点击此提示框,则其自动关闭;
- 弹出提示框后若在规定时间内点击该提示框,则正常返回所选选项数据。
代码如下:
public class MessageBoxTimeOut
{
private static string _caption;
private static Timer timer;
private static void StartTimer(int interval)
{
timer = new Timer();
timer.Interval = interval * 1000;
timer.Tick += (sender, e) =>
{
IntPtr ptr;
if (CheckMessageBox(out ptr))
{
KillMessageBox(ptr);
}
//timer.Enabled = false;
};
timer.Enabled = true;
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, int timeout)
{
_caption = caption;
StartTimer(timeout);
DialogResult result = MessageBox.Show(text, caption, buttons, icon);
timer.Stop();
return result;
}
[DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
private static extern bool EndDialog(IntPtr hDlg, out IntPtr nResult);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool IsWindow(IntPtr hWnd);
private static bool CheckMessageBox(out IntPtr ptr)
{
//ptr = FindWindow(null, _caption); // "#32770" 是 MessageBox 的类名
ptr = FindWindow("#32770", _caption);
return ptr != IntPtr.Zero && IsWindow(ptr);
}
private static void KillMessageBox(IntPtr ptr)
{
IntPtr res1;
EndDialog(ptr, out res1);
}
}
此时便可正常调用 MessageBox 去弹出定时自动关闭的提示框,代码如下
//DialogResult result = MessageBox.Show("your message", "title", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
DialogResult result = MessageBoxTimeOut.Show("your message", "title", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, 4);
但需注意,上述只实现了具有返回值的显示方式,没有返回值的提示框显示需微调上述代码。