.net - 如何防止在 FormClosing 事件中关闭和处置 Winform?

标签 .net winforms delphi-prism oxygene formclosing

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

我有一个 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 关闭和被处理。

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

提前致谢,

最佳答案

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

关于.net - 如何防止在 FormClosing 事件中关闭和处置 Winform?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11471266/

相关文章:

mono - 如何在单声道下强制应用程序的单个实例?

linux - 无法在 Mono 下加载 RemObjects.InternetPack

.net - 是否有 timeBeginPeriod 和 timeEndPeriod 方法的 .NET 替代品?

.net - Visual Studio 2012 InstallShield LE .NET Framework 4.5 先决条件

.net - 如何设置日期从和到月份的开始和结束日期?

c# - MDI WinForm 应用程序的奇怪任务栏行为

c# - 是什么让表单无法被隐藏?

c# - 检测添加到 ComboBox 的项目的事件

c# - 使用 XmlSerializer 时如何向 XML 文件写入注释?

c# - Access 2007 已锁定