信息提示框(MessageBox)是微軟NET自帶的一個用於彈出警告、錯誤或者訊息一類的“模式”對話框。此類對話框一旦開啟,則后台窗體無法再被激活(除非當前的MessageBox被點擊或者關閉取消)。那么如何使用程序模擬鼠標點擊這個messageBox(關閉這個MessageBox)呢?答案是你在彈出這個messageBox之前先啟用一個定時器,定時器內部不斷向窗體發送Enter按鈕用於模擬點擊MsgBox的內容,同時主程序中彈出模式消息框。代碼如下(VS2012 RC 編寫):
我們假設窗體上就一個Button,點擊這個Button將彈出5個msgbox,同時每個msgbox將延時2秒后自動關閉。
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);
}
}