C#MessageBox 自动关闭窗口

1:MessageBox弹出的模式窗口会先阻塞掉它的父级线程.所以我们可以考虑在MessageBox前先增加一个用于"杀"掉MessageBox窗口的线程.因为需要在规定时间内"杀"掉窗口

解决:可以考虑在MessageBox前先增加一个用于"杀"掉MessageBox窗口的线程.因为需要在规定时间内"杀"掉窗口,所以我们可以直接考虑使用Timer类.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace LeafSoft.Units
{
class KillMessageBox
{
[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 KillMessageBox()
{
}
public string caption="错误";
public void StartKiller()
{
Timer timer = new Timer();
timer.Interval = 6000; //3秒启动
timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
KillBoxMethod();
//停止Timer
((Timer)sender).Stop();
}
public void KillBoxMethod()
{
//按照MessageBox的标题,找到MessageBox的窗口
IntPtr ptr = FindWindow(null, caption);
if (ptr != IntPtr.Zero)
{
//找到则关闭MessageBox窗口
PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
}

}
}

 2:每次在使用MessageBox.Show()之前先用创建KillMessageBox对象实例

            KillMessageBox killbox = new KillMessageBox();
            killbox.caption = "异常";//caption变量为窗口的标题  可以设置默认值
            killbox.StartKiller();
            MessageBox.Show("你好", "异常");
原文地址:https://www.cnblogs.com/fyp7077/p/7507369.html