public partial class FrmButtonTimer : Form
{
#region 定时关闭MessageBox
[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;
public FrmButtonTimer()
{
InitializeComponent();
}
private void StartKiller(int getTime)
{
Timer SetTimer = new Timer(); //实例一个Timer物件,名称为SetTimer
SetTimer.Interval = (getTime * 1000); //x秒后启动
SetTimer.Tick += new EventHandler(SetTimer_Tick); // 建立一个触发Tick 事件
SetTimer.Start(); // 启动Timer (即 SetTimer 开始启动 )
}
void SetTimer_Tick(object sender, EventArgs e)
{
KillMessageBox(); // 执行MessageBox删除
((Timer)sender).Stop(); // 停止时间,转化为Timer类型
}
private void KillMessageBox()
{
// 按照MessageBox的标题,找出Messagebox这个视窗
IntPtr ptr = FindWindow(null, "Title!");
if (ptr != IntPtr.Zero) // 此表示只要 ptr 不为空值的内容时
{
//找到则关闭 MessageBox 視窗
PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
}
#endregion
private void btnTimerMessage_Click(object sender, EventArgs e)
{
StartKiller(2);
MessageBox.Show(" 2秒钟后,我会自动关闭!", "Title!");
}