使用计时器在 Messagebox 中启用按钮

Enabling Button in Messagebox with timer

我有一个消息框,它会在用户单击按钮时弹出。当用户单击“是”时,它是 运行 一个 insert 函数。

我想要的是在 messagebox 弹出时添加或开始倒计时,默认 yes button 被禁用。在 5 second yes button 之后,变为 enable 并准备好供用户点击。

  if (MessageBox.Show("log", "test", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {                  
                insert();
            }

正如评论中所建议的,您需要自己实现此功能。下面是部分代码,您需要修改普通表单以使其看起来像对话框:

  1. 向您的项目添加新的 Form。打开属性选项卡。设置属性如下点 2.

  2. 修改设计器中的表单以将以下属性更改为给定值:

    this.AcceptButton = this.btnYes;//To simulate clicking *ENTER* (Yes)
    this.CancelButton = this.button2; //to close form on *ESCAPE* button
    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
    this.MaximizeBox = false;
    this.MinimizeBox = false;
    //FROM CODEPROJECT ARTICLE LINK
    this.ShowInTaskBar = false;
    this.StartPosition = CenterScreen;
    
  3. 为表单添加一个计时器。将其间隔设置为 5000(5 秒)。编写代码以在 Shown 形式的事件上启动计时器:

    private void DialogBox_Shown(object sender, EventArgs e)
    {
        timer1.Start();
    }
    
  4. 处理定时器的滴答:

    public DialogBox()
    {
        InitializeComponent();
    
        //bind Handler to tick event. You can double click in 
        //properrties>events tab in designer
        timer1.Tick += Timer1_Tick;
    }
    
    private void Timer1_Tick(object sender, EventArgs e)
    {
        btnYes.Enabled = true;
        timer1.Stop();
    }
    
  5. 设置按钮处理程序:

    private void btnYes_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.Yes;
    }
    
  6. 从显示此自定义消息框的位置,您可以检查是否单击了 YesNo,如下所示:

    var d=new DialogBox();
    var result=d.ShowDialog();
    
    if(result==DialogResult.Yes)
    //here you go....