【问题标题】:How to prevent Closing and Disposing of a winform in the FormClosing event?如何防止在 FormClosing 事件中关闭和处置 Winform?
【发布时间】:2012-07-13 08:24:24
【问题描述】:

这个问题可能看起来像重复,但我在测试程序时遇到了这个问题,我对你如何解决它感到有点困惑。

我有一个 winform,它有一个表单关闭事件。在这种情况下,我会弹出一个消息框,询问用户“你确定要关闭窗口吗?”。如果他们按下是按钮,应用程序将关闭窗口并阻止它按预期进行处理。所以,我可以再次打开它。但是,如果他们没有按任何按钮,它仍然会关闭窗口,但现在窗口已被释放。因此,当我尝试再次打开它时,它引发了一个异常,“无法访问已处置的对象”。当按下 No 按钮时,我希望 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 关闭和被处理。

你是怎么解决这个问题的?

提前致谢,

【问题讨论】:

  • @mrazza 说得对。我会说如果你坚持使用 close = hide 你会遇到更多问题。我尽量避免这种事情。

标签: .net winforms delphi-prism oxygene formclosing


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多