我們在C#編程中常見的信息提示框(MessageBox)是微軟NET自帶的一個用于彈出警告、錯誤或者訊息一類的“模式”對話框。此類對話框一旦開啟,則后臺窗體無法再被激活(除非當前的MessageBox被點擊或者關閉取消)。那么如何使用程序模擬鼠標點擊這個messageBox(關閉這個MessageBox)令其延時并自動關閉呢?答案是你在彈出這個messageBox之前先啟用一個定時器,定時器內部不斷向窗體發送Enter按鈕用于模擬點擊MsgBox的內容,同時主程序中彈出模式消息框。
具體實現代碼如下(本程序運行測試環境基于VS2012 RC 編寫):
我們假設窗體上就只有一個Button,點擊這個Button將彈出5個msgbox,同時每個msgbox將延時2秒后自動關閉。
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) NextEnd sub) act.BeginInvoke(Nothing, Nothing) End SubEnd Class
此外需要注意:
1.這里使用了“委托異步”是為了防止主線程被Thread延時導致假死的情況發生。
2.SendKeys這里必須使用SendWait,否則會拋出異常。
新聞熱點
疑難解答