Messagebox Buttons access in C#

81 views Asked by At

I am using timer in my code, lets say when timer stops at 0, messagebox prompts me that you timed out and shows two buttons "RETRY" and "CANCEL". Guide me with the functionality i.e when I press "CANCEL" button on messagebox, it exits the entire windows form. below is the if condition to the timer_tick event:

    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

There are 2 answers

0
Aluan Haddad On BEST ANSWER

To work with MessageBox and take a different action depending on the button clicked, one must assign the result of the Show call to a variable. Show returns a DialogResult value which you can use to determine which button was clicked.

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();
}
0
Deepak Tiwari On

You can do something like this below code:

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

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