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

ThN*_*ThN 3 .net oxygene delphi-prism winforms formclosing

这个问题可能看似重复,但我在测试程序时遇到了这个问题,我对你如何解决它感到困惑.

我有一个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;
Run Code Online (Sandbox Code Playgroud)

我想,因为你必须设置e.Cancel = true来关闭窗口并告诉它隐藏,做相反的事情(e.Cancel = false并且没有隐藏)将阻止winform关闭和被处理.

你是如何解决这个问题的?

预先感谢,

Mat*_*zza 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
Run Code Online (Sandbox Code Playgroud)

e.Cancel := true;防止窗口关闭.然后提示用户,如果他们说是Hide;隐藏窗口(没有处理).如果用户单击否,则不会发生任何操作.

检测正在执行何种近距离动作可能是个好主意.使用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
Run Code Online (Sandbox Code Playgroud)