c# 定時關閉 MessageBox 或彈出的模態窗口

咱們都知道,MessageBox彈出的窗口是模式窗口,模式窗口會自動阻塞父線程的。因此若是有如下代碼:javascript

MessageBox.Show("內容',"標題"); 

則只有關閉了MessageBox的窗口後纔會運行下面的代碼。而在某些場合下,咱們又須要在必定時間內若是在用戶尚未關閉窗口時能自動關閉掉窗口而避免程序一直停留不前。這樣的話咱們怎麼作呢?上面也說了,MessageBox彈出的模式窗口會先阻塞掉它的父級線程。因此咱們能夠考慮在MessageBox前先增長一個用於「殺」掉MessageBox窗口的線程。由於須要在規定時間內「殺」掉窗口,因此咱們能夠直接考慮使用Timer類,而後調用系統API關閉窗口。html

 

核心代碼以下:java

複製代碼
[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 的效果。  post

 

出處:http://www.javashuo.com/article/p-akkolgly-gn.html測試

=======================================================================this

通過測試,這個方法沒辦法關閉下面的代碼彈出窗口:spa

new ViewMessage().ShowDialog(this);   //我彈出的模態窗口,而且指定主窗口的類爲this線程

我是經過下面的代碼獲取窗口並關閉code

private void ExitAllForm()
{
    var fs = System.Windows.Forms.Application.OpenForms;
    for (int i = 0; i < fs.Count; i++)
    {
        //........邏輯代碼
       KillForm(fs[i].Text);
    }
}

        private void KillForm(string strTitle)
        {
            IntPtr ptr = Common.WindowsAPI.FindWindow(null, strTitle);
            if (ptr != IntPtr.Zero)
            {
                Common.WindowsAPI.PostMessage(ptr, 0x10, IntPtr.Zero, IntPtr.Zero);
            }
        }



        /// <summary>
        /// 獲取指定標題窗口的句柄
        /// </summary>
        /// <param name="lpClassName"></param>
        /// <param name="lpWindowName"></param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);


        /// <summary>
        /// 向指定窗口句柄發送消息
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="msg"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
相關文章
相關標籤/搜索