2014-03-12 45 views
2

我有一個名爲Form_Main的主表單,當有人想關閉它時,它會關閉整個應用程序(我的意思是完整的應用程序,我的意思是退出其他表單)。因此,我準備了一個是/否的MessageBox,詢問用戶是否真的要退出該表單。這裏是我在哪裏:禁止用戶關閉表格

private void Form_Main_FormClosed(object sender, FormClosedEventArgs e) 
{ 
     DialogResult result = MessageBox.Show("Are you sure?", "Confirmation", MessageBoxButtons.OKCancel); 
     if (result == DialogResult.OK) 
     { 
      Environment.Exit(1); 
     } 
     else 
     { 
      //does nothing 
     } 
} 

「確定」按鈕的作品。但是當用戶點擊「取消」時,Form_Main已關閉,但應用程序仍在運行(其他表單未觸及)。我應該用什麼替換//does nothing

回答

6

使用FormClosing事件(而不是FormClosed),然後設置e.Cancel = true

private void Form_Main_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    var result = MessageBox.Show("Are you sure?", "Confirmation", MessageBoxButtons.OKCancel); 

    e.Cancel = (result != DialogResult.OK); 
} 

FormClosing事件發生前的形式實際上關閉,所以你仍然有機會取消。在您參加FormClosed活動時,已爲時過晚。

+0

當然,如果你在'FormClosing'中,沒有必要用'Environment.Exit()'來進一步加速,現在是嗎? – DonBoitnott

+0

@DonBoitnott通常不會,但我不知道如何設置Anggrian的環境。他表示,如果表單剛剛關閉(沒有Environment.Exit),則其他表單將保持打開狀態。 –

+0

在FormClosing中,我在Environment.Exit(1) –