咱们都知道,MessageBox弹出的窗口是模式窗口,模式窗口会自动阻塞父线程的。因此若是有如下代码:spa
MessageBox.Show("内容',"标题");
则只有关闭了MessageBox的窗口后才会运行下面的代码。而在某些场合下,咱们又须要在必定时间内若是在用户尚未关闭窗口时能自动关闭掉窗口而避免程序一直停留不前。这样的话咱们怎么作呢?上面也说了,MessageBox弹出的模式窗口会先阻塞掉它的父级线程。因此咱们能够考虑在MessageBox前先增长一个用于“杀”掉MessageBox窗口的线程。由于须要在规定时间内“杀”掉窗口,因此咱们能够直接考虑使用Timer类,而后调用系统API关闭窗口。线程
核心代码以下:code
[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; 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的弹出窗口,注意MessageBox对应的标题 IntPtr ptr = FindWindow(null,"标题"); if(ptr != IntPtr.Zero) { //查找到窗口则关闭 PostMessage(ptr,WM_CLOSE,IntPtr.Zero,IntPtr.Zero); } }
在须要的地方调用 StartKiller 方法便可达到自动关闭 MessageBox 的效果。 blog