2012-07-13 92 views
3

這個問題可能看起來像重複,但我在測試我的程序時碰到了這個問題,我對你如何解決它感到困惑。如何防止在FormClosing事件中關閉和處理winform?

我有一個winform,它有一個窗體關閉事件。在這種情況下,我彈出一個消息框,詢問用戶「你確定要關閉窗口嗎?」。如果他們按了「是」按鈕,應用程序將關閉窗口,並防止按預期處理它。所以,我可以再次打開它。但是,如果他們不按任何按鈕,它仍會關閉窗口,但現在窗口已被處理。所以,當我嘗試再次打開它時,它引發了一個異常,「無法訪問已處理的對象」。當沒有按鈕被按下時,我希望Winform保持打開狀態並且不會丟棄。

這裏是我的代碼:

method PPMain.PPMain_FormClosing(sender: System.Object; e: System.Windows.Forms.FormClosingEventArgs); 
begin 
     if MessageBox.Show('Are you sure you want to close the window?','PPMain',MessageBoxButtons.YesNo) = DialogResult.Yes then 
     begin 
      e.Cancel := true; 
      Hide; 
     end 
     else 
      e.Cancel := false; 
end; 

我想既然你要設置e.Cancel = true來關閉該窗口,並告訴它隱藏起來,做的是相反的(e.Cancel =假,沒有隱藏)將阻止winform關閉並被丟棄。

你如何解決這個問題?

預先感謝,

+1

@mrazza叫這個權利。如果你堅持close = hide的話,我會說你會碰到更多的問題。我嘗試避免這種事情。 – 2012-07-13 13:40:18

回答

10

e.Cancel = true防止關閉該窗口 - 它停止關閉事件。

e.Cancel = false允許「關閉事件」繼續(導致窗口關閉並被丟棄;假設沒有其他東西會阻止它)。

看來你想這樣做:

method PPMain.PPMain_FormClosing(sender: System.Object; e: System.Windows.Forms.FormClosingEventArgs); 
begin 
     e.Cancel := true; 
     if MessageBox.Show('Are you sure you want to close the window?','PPMain',MessageBoxButtons.YesNo) = DialogResult.Yes then 
     begin 
      Hide; 
     end 
end 

e.Cancel := true;防止關閉該窗口。然後提示用戶,如果他們說yes隱藏窗口(不處理)。如果用戶點擊否,則不會發生任何事情。

檢測正在執行什麼樣的關閉操作可能是一個好主意。使用e.CloseReason以防止在OS關閉期間關閉或沿着這些線路進行關閉。

像這樣:

method PPMain.PPMain_FormClosing(sender: System.Object; e: System.Windows.Forms.FormClosingEventArgs); 
begin 
     if e.CloseReason = System.Windows.Forms.CloseReason.UserClosing then 
     begin 
      e.Cancel := true; 
      if MessageBox.Show('Are you sure you want to close the window?','PPMain',MessageBoxButtons.YesNo) = DialogResult.Yes then 
      begin 
       Hide; 
      end 
     end 
end 
+0

很好用謝謝。 – ThN 2012-07-13 14:05:16