C#實現(xiàn)延時并自動關(guān)閉MessageBox的方法
我們在C#編程中常見的信息提示框(MessageBox)是微軟NET自帶的一個用于彈出警告、錯誤或者訊息一類的“模式”對話框。此類對話框一旦開啟,則后臺窗體無法再被激活(除非當前的MessageBox被點擊或者關(guān)閉取消)。那么如何使用程序模擬鼠標點擊這個messageBox(關(guān)閉這個MessageBox)令其延時并自動關(guān)閉呢?答案是你在彈出這個messageBox之前先啟用一個定時器,定時器內(nèi)部不斷向窗體發(fā)送Enter按鈕用于模擬點擊MsgBox的內(nèi)容,同時主程序中彈出模式消息框。
具體實現(xiàn)代碼如下(本程序運行測試環(huán)境基于VS2012 RC 編寫):
我們假設(shè)窗體上就只有一個Button,點擊這個Button將彈出5個msgbox,同時每個msgbox將延時2秒后自動關(guān)閉。
C#功能代碼如下:
public partial class Form1 : Form
{
private System.Windows.Forms.Timer[] ts = new System.Windows.Forms.Timer[6];
public Form1()
{
InitializeComponent();
}
void t_Tick(object sender, EventArgs e)
{
((System.Windows.Forms.Timer)sender).Enabled = false;
SendKeys.SendWait("{Enter}");
}
private void button1_Click(object sender, EventArgs e)
{
Action act = new Action(() =>
{
for (int i = 0; i < 6; i++)
{
ts[i] = new System.Windows.Forms.Timer();
ts[i].Tick += t_Tick;
ts[i].Interval = 2000;
ts[i].Enabled = true;
MessageBox.Show("MsgBox" + (i + 1));
Thread.Sleep(2000);
}
});
act.BeginInvoke(null, null);
}
}
Public Partial Class Form1
Inherits Form
Private ts As System.Windows.Forms.Timer() = New System.Windows.Forms.Timer(5) {}
Public Sub New()
InitializeComponent()
End Sub
Private Sub t_Tick(sender As Object, e As EventArgs)
DirectCast(sender, System.Windows.Forms.Timer).Enabled = False
SendKeys.SendWait("{Enter}")
End Sub
Private Sub button1_Click(sender As Object, e As EventArgs)
Dim act As New Action(Sub()
For i As Integer = 0 To 5
ts(i) = New System.Windows.Forms.Timer()
AddHandler ts(i).Tick, AddressOf t_Tick
ts(i).Interval = 2000
ts(i).Enabled = True
MessageBox.Show("MsgBox" & (i + 1))
Thread.Sleep(2000)
Next
End sub)
act.BeginInvoke(Nothing, Nothing)
End Sub
End Class
此外需要注意:
1.這里使用了“委托異步”是為了防止主線程被Thread延時導致假死的情況發(fā)生。
2.SendKeys這里必須使用SendWait,否則會拋出異常。
相關(guān)文章
利用Aspose.Word控件實現(xiàn)Word文檔的操作
偶然一次機會,一個項目的報表功能指定需要導出為Word文檔,因此尋找了很多篇文章,不過多數(shù)介紹的比較簡單一點,于是也參考了官方的幫助介紹,終于滿足了客戶的需求。下面我由淺入深來介紹這個控件在實際業(yè)務中的使用過程吧2013-05-05
Windows下C#的GUI窗口程序中實現(xiàn)調(diào)用Google Map的實例
這篇文章主要介紹了Windows下C#的GUI窗口程序中實現(xiàn)調(diào)用Google Map的實例,如果只想調(diào)用瀏覽器打開網(wǎng)頁的話可以看文章最后的方法,需要的朋友可以參考下2016-04-04
探討:關(guān)閉瀏覽器后,php腳本會不會繼續(xù)運行
本篇文章是對關(guān)閉瀏覽器后,php腳本會不會繼續(xù)運行進行了詳細的分析介紹,需要的朋友參考下2013-06-06

