using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Mesnac.Basic
{
///
/// 自动超时消息提示框
///
public class MessageBoxTimeOut
{
///
/// 标题
///
private static string _caption;
///
/// 显示消息框
///
/// 消息内容
/// 标题
/// 超时时间,单位:毫秒
public static void Show(string text, string caption, int timeout)
{
_caption = caption;
StartTimer(timeout);
MessageBox.Show(text, caption);
}
///
/// 显示消息框
///
/// 消息内容
/// 标题
/// 超时时间,单位:毫秒
/// 消息框上的按钮
public static void Show(string text, string caption, int timeout, MessageBoxButtons buttons)
{
_caption = caption;
StartTimer(timeout);
MessageBox.Show(text, caption, buttons);
}
///
/// 显示消息框
///
/// 消息内容
/// 标题
/// 超时时间,单位:毫秒
/// 消息框上的按钮
/// 消息框上的图标
public static void Show(string text, string caption, int timeout, MessageBoxButtons buttons, MessageBoxIcon icon)
{
_caption = caption;
StartTimer(timeout);
MessageBox.Show(text, caption, buttons, icon);
}
///
/// 显示消息框
///
/// 消息框所有者
/// 消息内容
/// 标题
/// 超时时间,单位:毫秒
public static void Show(IWin32Window owner, string text, string caption, int timeout)
{
_caption = caption;
StartTimer(timeout);
MessageBox.Show(owner, text, caption);
}
///
/// 显示消息框
///
/// 消息框所有者
/// 消息内容
/// 标题
/// 超时时间,单位:毫秒
/// 消息框上的按钮
public static void Show(IWin32Window owner, string text, string caption, int timeout, MessageBoxButtons buttons)
{
_caption = caption;
StartTimer(timeout);
MessageBox.Show(owner, text, caption, buttons);
}
///
/// 显示消息框
///
/// 消息框所有者
/// 消息内容
/// 标题
/// 超时时间,单位:毫秒
/// 消息框上的按钮
/// 消息框上的图标
public static void Show(IWin32Window owner, string text, string caption, int timeout, MessageBoxButtons buttons, MessageBoxIcon icon)
{
_caption = caption;
StartTimer(timeout);
MessageBox.Show(owner, text, caption, buttons, icon);
}
private static void StartTimer(int interval)
{
Timer timer = new Timer();
timer.Interval = interval;
timer.Tick += new EventHandler(Timer_Tick);
timer.Enabled = true;
}
private static void Timer_Tick(object sender, EventArgs e)
{
KillMessageBox();
//停止计时器
((Timer)sender).Enabled = false;
}
[DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private extern static int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
private const int WM_CLOSE = 0x10;
private static void KillMessageBox()
{
//查找MessageBox的弹出窗口,注意对应标题
IntPtr ptr = FindWindow(null, _caption);
if (ptr != IntPtr.Zero)
{
//查找到窗口则关闭
PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
}
}
}