【问题标题】:Messagebox Buttons access in C#C# 中的消息框按钮访问
【发布时间】:2017-05-13 12:51:41
【问题描述】:

我在我的代码中使用了计时器,假设当计时器停止在 0 时,消息框会提示我您已超时并显示两个按钮“重试”和“取消”。指导我使用该功能,即当我按下消息框上的“取消”按钮时,它会退出整个 Windows 窗体。 下面是 timer_tick 事件的 if 条件:

    int duration = 10;

    private void timer1_Tick(object sender, EventArgs e)
    {
        //shows message that time is up!
       duration--;
       timer_label1.Text = duration.ToString();
       if (duration == 0)
       {
           timer1.Stop();
           MessageBox.Show("You Timed Out", "Oops", MessageBoxButtons.RetryCancel, MessageBoxIcon.Stop);

       } 
    }

    private void start_game_button19_Click(object sender, EventArgs e)
    {
        timer1.Enabled = true;
        timer1.Start();
    }

enter image description here

【问题讨论】:

  • 请发布您到目前为止尝试过的内容,以便我们为您提供帮助..
  • int 持续时间 = 10; private void timer1_Tick(object sender, EventArgs e) { //显示时间到的消息!期间 - ; timer_label1.Text=duration.ToString(); if (duration == 0) { timer1.Stop(); MessageBox.Show("你超时了", "糟糕", MessageBoxButtons.RetryCancel, MessageBoxIcon.Stop); } } private void start_game_button19_Click(object sender, EventArgs e) { timer1.Enabled = true; timer1.Start(); }
  • 您可以编辑您的原始帖子。评论区的长代码并没有真正的帮助。
  • 抱歉这里的代码格式错误

标签: c# winforms visual-studio visual-programming


【解决方案1】:

要使用MessageBox 并根据单击的按钮采取不同的操作,必须将Show 调用的结果分配给一个变量。 Show 返回一个 DialogResult 值,您可以使用它来确定单击了哪个按钮。

var retryOrCancel = MessageBox.Show(
    text: "You Timed Out",
    caption: "Oops",
    buttons: MessageBoxButtons.RetryCancel,
    icon: MessageBoxIcon.Stop
);

switch (retryOrCancel)
{
    case DialogResult.Cancel:
    this.Close();
    break;
    case DialogResult.Retry:
    StartGame();
    break;
}

private void start_game_button19_Click(object sender, EventArgs e)
{
    StartGame();
}

private void StartGame() 
{
    timer1.Enabled = true;
    timer1.Start();
}

【讨论】:

  • 很高兴为您提供帮助。如果您觉得这个答案很好地说明了问题,请投票给它。
【解决方案2】:

你可以在下面的代码中做这样的事情:

var result =  MessageBox.Show(
              "You Timed Out",
              "Oops",
              MessageBoxButtons.RetryCancel,
              MessageBoxIcon.Stop);

if (result == DialogResult.Cancel) {
    this.Close();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多