0

我有VS2015 Windows窗體,每當我點擊X關閉應用程序,它都會提示我關閉它。當我按「否」時,彈出窗口將關閉。但是,當我按是時,它會彈出另一個窗口,並要求我關閉它。VS2015關閉Windows窗體無法正常工作

我該如何解決這個問題?我想先關閉我的表單。

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
     { 
      const string closemsg = "Do you really want to close the program?"; 
      const string exit = "Exit"; 

      DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo); 

      if (dialog == DialogResult.Yes) 
      { 
       Application.Exit(); 
      } 
      else if (dialog == DialogResult.No) 
      { 
       e.Cancel = true; 
      } 
     } 
+0

你確定需要'Application.Exit();'?如果你什麼都不做,並返回離開'e.Cancel'爲假? –

回答

2

這是非常簡單的。 Make remove Application.Exit();

Application.Exit()生成FormClosing事件。

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    const string closemsg = "Do you really want to close the program?"; 
    const string exit = "Exit"; 

    DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo); 

    if (dialog == DialogResult.Yes) 
    { 
     //Remove Application.Exit(); 
     //Application.Exit(); 
    } 
    else if (dialog == DialogResult.No) 
    { 
     e.Cancel = true; 
    } 
} 
+0

謝謝!這一個也工作@ –

+0

Doh!我忘了:P這裏有+1 – MickyD

+0

@羅伊謝謝! – Hojin

1

然而,當我按是,它會彈出另一個同一個窗口,並要求我關閉與否。

原因是因爲您的Form1_FormClosing將被再次調用。嘗試設置一個_isExiting標誌,您可以在輸入時進行測試。

試試這個:

bool _isExiting; 

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    if (_isExiting) 
    { 
     // whoops, been here already, time to go! 
     return; 
    } 

    const string closemsg = "Do you really want to close the program?"; 
    const string exit = "Exit"; 

    DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo); 

    if (dialog == DialogResult.Yes) 
    { 
     _isExiting=true; // set flag here so we don't repeat this exercise again 
     Application.Exit(); 
    } 
    else if (dialog == DialogResult.No) 
    { 
     e.Cancel = true; 
    } 
} 
+0

謝謝!它運作良好! –

+0

謝謝你,先生。 – MickyD