methuselah
methuselah

Reputation: 13216

Exit C# application from second form

How do I exit a C# application completely from the second form when the user presses the X button?

This is my code so far:

Form1.cs

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 1)
        {
            String cellValue;
            cellValue = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
            var form2 = new Form2(cellValue);
            this.Hide();
            form2.Show();
        }
    }
    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        base.OnFormClosing(e);

        if (e.CloseReason == CloseReason.WindowsShutDown) return;

        switch (MessageBox.Show(this, "Are you sure you want to exit?", "", MessageBoxButtons.YesNo))
        {
            case DialogResult.No:
                e.Cancel = true;
                break;
            default:
                break;
        }
    }

Form2.cs

protected override void OnFormClosing(FormClosingEventArgs e)
{
    base.OnFormClosing(e);

    if (e.CloseReason == CloseReason.WindowsShutDown) return;

    switch (MessageBox.Show(this, "Are you sure you want to exit?", "", MessageBoxButtons.YesNo))
    {
        case DialogResult.No:
            e.Cancel = true;
            break;
        default:
            break;
    }
}

Upvotes: 0

Views: 399

Answers (2)

Jaime Torres
Jaime Torres

Reputation: 10515

Based on comments, sounds like this is a workable solution:

private bool userRequestedExit = false;
protected override void OnFormClosing(FormClosingEventArgs e)
{
    base.OnFormClosing(e);

    if (this.userRequestedExit) {
        return;
    }

    if (e.CloseReason == CloseReason.WindowsShutDown) return;

    switch (MessageBox.Show(this, "Are you sure you want to exit?", "", MessageBoxButtons.YesNo))
    {
        case DialogResult.No:
            e.Cancel = true;
            break;
        default:
            this.userRequestedExit = true;
            Application.Exit();
            break;
    }
}

Upvotes: 2

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13784

protected override void OnFormClosing(FormClosingEventArgs e)
{


   DialogResult dgResult = MessageBox.Show(this, "Are you sure you want to exit?", "", MessageBoxButtons.YesNo); 
    if(dgResult==DialogResult.No)
            e.Cancel = true;

      else
     //here  you can use  Environment.Exit  which is not recomended because it does not generate a message loop to notify others form
      Environment.Exit(1);  
        //or  you can use
         //Application.Exit();  
}

Upvotes: 3

Related Questions