国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C# > 正文

C#實(shí)現(xiàn)延時(shí)并自動(dòng)關(guān)閉MessageBox的方法

2020-01-24 02:35:53
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

我們?cè)贑#編程中常見(jiàn)的信息提示框(MessageBox)是微軟NET自帶的一個(gè)用于彈出警告、錯(cuò)誤或者訊息一類的“模式”對(duì)話框。此類對(duì)話框一旦開(kāi)啟,則后臺(tái)窗體無(wú)法再被激活(除非當(dāng)前的MessageBox被點(diǎn)擊或者關(guān)閉取消)。那么如何使用程序模擬鼠標(biāo)點(diǎn)擊這個(gè)messageBox(關(guān)閉這個(gè)MessageBox)令其延時(shí)并自動(dòng)關(guān)閉呢?答案是你在彈出這個(gè)messageBox之前先啟用一個(gè)定時(shí)器,定時(shí)器內(nèi)部不斷向窗體發(fā)送Enter按鈕用于模擬點(diǎn)擊MsgBox的內(nèi)容,同時(shí)主程序中彈出模式消息框。

具體實(shí)現(xiàn)代碼如下(本程序運(yùn)行測(cè)試環(huán)境基于VS2012 RC 編寫):

我們假設(shè)窗體上就只有一個(gè)Button,點(diǎn)擊這個(gè)Button將彈出5個(gè)msgbox,同時(shí)每個(gè)msgbox將延時(shí)2秒后自動(dòng)關(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)    NextEnd sub)    act.BeginInvoke(Nothing, Nothing)  End SubEnd Class

此外需要注意:

1.這里使用了“委托異步”是為了防止主線程被Thread延時(shí)導(dǎo)致假死的情況發(fā)生。

2.SendKeys這里必須使用SendWait,否則會(huì)拋出異常。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 格尔木市| 常宁市| 木兰县| 哈尔滨市| 兴文县| 成安县| 鲁甸县| 宿松县| 西城区| 贺兰县| 宕昌县| 曲周县| 育儿| 旌德县| 沧州市| 抚州市| 红河县| 南漳县| 扬州市| 灵武市| 商丘市| 宜宾市| 奈曼旗| 长泰县| 新乐市| 抚顺县| 南澳县| 青海省| 石家庄市| 淄博市| 黎川县| 乌拉特中旗| 巨野县| 成都市| 天台县| 调兵山市| 汉川市| 镇雄县| 山丹县| 藁城市| 藁城市|