C#窗體MessageBox顯示自動消失


【說明】引自:http://xgli0910.blog.163.com/blog/static/4696216820127601455221/

【前言】 MessageBox提示框一般需要手動關閉,對於簡單的信息提示,每次還要去關閉很麻煩。於是想到怎樣能讓MessageBox顯示一段時間后自動關閉。

【代碼】

 1 C#窗體MessageBox顯示自動消失
 2 
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Text;
 6 using System.Runtime.InteropServices;
 7 using System.Windows.Forms;
 8 
 9 namespace pdaTraceInfoPlat.beans
10 {
11     class MessageBoxTimeOut
12     {
13         private string _caption;
14 
15         public void Show(string text, string caption, int timeout)
16         {
17             this._caption = caption;
18             StartTimer(timeout);
19             MessageBox.Show(text, caption);
20         }
21 
22         private void StartTimer(int interval)
23         {
24             Timer timer = new Timer();
25             timer.Interval = interval;
26             timer.Tick += new EventHandler(Timer_Tick);
27             timer.Enabled = true;
28         }
29 
30         private void Timer_Tick(object sender, EventArgs e)
31         {
32             KillMessageBox();
33             //停止計時器
34             ((Timer)sender).Enabled = false;
35         }
36 
37         [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
38         private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
39 
40         [DllImport("user32.dll", CharSet = CharSet.Auto)]
41         public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
42 
43         public const int WM_CLOSE = 0x10;
44 
45         private void KillMessageBox()
46         {
47             //查找MessageBox的彈出窗口,注意對應標題
48             IntPtr ptr = FindWindow(null, this._caption);
49             if (ptr != IntPtr.Zero)
50             {
51                 //查找到窗口則關閉
52                 PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
53             }
54         }       
55     }
56 }

【注意】  windows系統中,DllImport應為user32.dll,即[DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)],

而不是   [DllImport("coredll.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM