我們都知道,MessageBox彈出的窗口是模式窗口,模式窗口會自動阻塞父線程的。所以如果有以下代碼:
MessageBox.Show("內容',"標題");
則只有關閉了MessageBox的窗口后才會運行下面的代碼。而在某些場合下,我們又需要在一定時間內如果在用戶還沒有關閉窗口時能自動關閉掉窗口而避免程序一直停留不前。這樣的話我們怎么做呢?上面也說了,MessageBox彈出的模式窗口會先阻塞掉它的父級線程。所以我們可以考慮在MessageBox前先增加一個用於“殺”掉MessageBox窗口的線程。因為需要在規定時間內“殺”掉窗口,所以我們可以直接考慮使用Timer類,然后調用系統API關閉窗口。
核心代碼如下:
[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 的效果。