2013-12-14 47 views
0

當用戶按下X按鈕時,如何從第二個窗體完全退出C#應用程序?從第二個窗體退出C#應用程序

這是我到目前爲止的代碼:基於評論

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; 
    } 
} 

回答

3
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(); 
} 
+0

對話框出現三次因某種原因,用戶必須點擊「是」,每次否則程序崩潰 – methuselah

+0

現在就來試試它,請讓我知道,如果出現錯誤但 –

+0

同樣的事情 - 它真的奇數:-S – methuselah

2

,聽起來這是一個可行的解決方案:

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; 
    } 
} 
相關問題