在一些程序中,我們會(huì)發(fā)現(xiàn)彈出的的對(duì)話框會(huì)自動(dòng)關(guān)閉,那么在C#的WinForm中是否也可以實(shí)現(xiàn)這種功能呢? 下面轉(zhuǎn)載了cnblogs.com eaglet的一篇文章,該文章中使用API函數(shù)來實(shí)現(xiàn)該功能。
WinForm中可以調(diào)用MessageBox.Show 來顯示一個(gè)消息對(duì)話框,提示用戶確認(rèn)等操作。在有些應(yīng)用中我們需要通過程序來自動(dòng)關(guān)閉這個(gè)消息對(duì)話框而不是由用戶點(diǎn)擊確認(rèn)按鈕來關(guān)閉。然而.Net framework 沒有為我們提供自動(dòng)關(guān)閉MessageBox 的方法,要實(shí)現(xiàn)這個(gè)功能,我們需要使用Window API 來完成。
首先我們需要找到這個(gè)消息對(duì)話框的窗口句柄,一個(gè)比較簡(jiǎn)單的方法就是用 FindWindow API 來查找對(duì)應(yīng)的窗體句柄。
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
這個(gè)API調(diào)用可以通過窗口的類名或者窗口標(biāo)題的名字來查找窗口句柄。接下來我們還需要找到一個(gè) API 來關(guān)閉對(duì)話框,這里我使用 EndDialog
[DllImport("user32.dll")]
static extern bool EndDialog(IntPtr hDlg, out IntPtr nResult);
有了這兩個(gè)API函數(shù),我們就可以來關(guān)閉消息對(duì)話框了。思路是在調(diào)用MessageBox.Show 前啟動(dòng)一個(gè)后臺(tái)工作線程,這個(gè)工作線程等待一定時(shí)間后開始查找消息對(duì)話框的窗口句柄,找到后調(diào)用EndDialog API 函數(shù)關(guān)閉這個(gè)消息對(duì)話框。不過這個(gè)方法有個(gè)問題,就是如果同時(shí)又多個(gè)同名的消息對(duì)話框(可能不一定是這個(gè)應(yīng)用的),這樣做可能會(huì)關(guān)錯(cuò)窗口,如何解決這個(gè)問題,我還沒有想出比較好的方法,如果大家有更好的方法解決這個(gè)問題,不妨一起討論討論。
我根據(jù)這個(gè)思路編寫了延時(shí)關(guān)閉消息對(duì)話框的函數(shù)
public void ShowMessageBoxTimeout(string text, string caption,
MessageBoxButtons buttons, int timeout)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(CloseMessageBox),
new CloseState(caption, timeout));
MessageBox.Show(text, caption,buttons);
}
這個(gè)函數(shù)中timeout 參數(shù)單位是毫秒,其他參數(shù)和MessageBox.Show的參數(shù)含義是一樣的,這里不再詳細(xì)說明。
這個(gè)函數(shù)中首先利用線程池調(diào)用一個(gè)工作線程 CloseMessageBox ,并將對(duì)話框的標(biāo)題和延時(shí)時(shí)間通過CloseState這個(gè)類傳遞給CloseMessageBox函數(shù)。
CloseState 的定義如下:
private class CloseState
{
private int _Timeout;/**//// <summary>
/// In millisecond
/// </summary>
public int Timeout
{
get
{
return _Timeout;
}
}private string _Caption;/**//// <summary>
/// Caption of dialog
/// </summary>
public string Caption
{
get
{
return _Caption;
}
}public CloseState(string caption, int timeout)
{
_Timeout = timeout;
_Caption = caption;
}
}
最后就是CloseMessageBox函數(shù)了,直接看代碼吧
private void CloseMessageBox(object state)
{
CloseState closeState = state as CloseState;Thread.Sleep(closeState.Timeout);
IntPtr dlg = FindWindow(null, closeState.Caption);if (dlg != IntPtr.Zero)
{
IntPtr result;
EndDialog(dlg, out result);
}
}
新聞熱點(diǎn)
疑難解答