How to prevent Closing and Disposing of a winform in the FormClosing event?

前端 未结 1 368
深忆病人
深忆病人 2021-01-14 15:06

This question may seem like a duplicate, but I just ran in to this issue while I was testing my program and I am kind of confused as to how you solve it.

I have a wi

相关标签:
1条回答
  • 2021-01-14 15:29

    e.Cancel = true prevents the window from closing - it stops the close event.

    e.Cancel = false allows the "close event" to continue (resulting in the window closing and being disposed; assuming nothing else stops it).

    It seems you want to do this:

    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; prevents the window from closing. The user is then prompted, if they say yes Hide; hides the window (without disposing). If the user clicks No, nothing happens.

    It might be a good idea to detect what kind of close action is being performed. Using e.CloseReason so as not to prevent closing during OS shutdown or something along those lines.

    Like this:

    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 讨论(0)
提交回复
热议问题