Messagebox按钮访问C#

时间:2017-05-13 12:51:42

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

我在我的代码中使用计时器,假设当计时器停在0时,消息框提示我你超时并显示两个按钮“RETRY”和“CANCEL”。指导我的功能,即当我按下消息框上的“取消”按钮时,它退出整个窗体。 下面是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

2 个答案:

答案 0 :(得分:0)

要使用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();
}

答案 1 :(得分:0)

您可以在下面的代码中执行以下操作:

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

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