如何在FormClosing事件中防止关闭和处理winform?

3
这个问题看起来可能像是重复的,但在我的程序测试中我刚刚遇到了这个问题,我有点困惑如何解决它。
我有一个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=false且不隐藏)将防止winform关闭和被处理。

您如何解决这个问题?

提前致谢。


1
@mrazza 这次说得对。如果你坚持使用 close = hide,我会说你会遇到更多问题。但我个人会尝试避免这种情况。 - Tony Hopkinson
1个回答

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;可以防止窗口关闭。如果用户选择是,则Hide;会隐藏该窗口(但不会将其释放)。如果用户选择否,则不会发生任何事情。

检测正在执行的关闭操作可能是一个好主意。使用e.CloseReason来避免在操作系统关机等情况下阻止关闭。

像这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接