C#实现延时并自动关闭实现延时并自动关闭MessageBox的方法的方法
主要介绍了C#实现延时并自动关闭MessageBox的方法,非常实用的功能,需要的朋友可以参考下
我们在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)
Next
End sub)
act.BeginInvoke(Nothing, Nothing)
评论0