延时并自动关闭MessageBox

信息提示框(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);
        }

    }

[VB.NET]

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延时导致假死的情况发生。

注意2:SendKeys这里必须使用SendWait,否则会抛出异常。

转载于:https://www.cnblogs.com/ServiceboyNew/archive/2012/07/02/2573406.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值