【问题标题】:C# Form X Button ClickedC# Form X 按钮被点击
【发布时间】:2010-09-17 13:40:45
【问题描述】:

如何查看表单是否通过单击 X 按钮或 (this.Close()) 关闭?

【问题讨论】:

  • 这个比给它写代码更简单。

标签: c# winforms


【解决方案1】:

表单有事件FormClosing,参数类型为FormClosingEventArgs

// catch the form closing event
private void Form1_FormClosing( object sender, FormClosingEventArgs e )
{
    // check the reason (UserClosing)
    if ( e.CloseReason == CloseReason.UserClosing )
    {
        // do stuff like asking user
        if ( MessageBox.Show( this,
                 "Are you sure you want to close the form?",
                 "Closing Form",
                 MessageBoxButtons.OKCancel,
                 MessageBoxIcon.Question ) == DialogResult.Cancel )
         {
             // cancel the form closing if necessary
             e.Cancel = true;
         }
    }
}

【讨论】:

  • 我不想问是否真的很接近。我的表单有一个取消按钮,在单击取消时,我将一个将返回的字段设置为空。从外面,我知道当这个表单返回 null 时我不必做任何事情。但是当通过单击 X 关闭表单时,该字段不为空,因此外部代码崩溃。
【解决方案2】:

您可以完全删除“X”吗?

表单的属性之一是“ControlBox”,只需将其设置为false

【讨论】:

    【解决方案3】:

    如果您想将返回的字段设置为 null,就像您在表单中单击“取消”时所做的那样:

    private void Form1_FormClosing( object sender, FormClosingEventArgs e )
    {
        if ( e.CloseReason == CloseReason.UserClosing )
        {
            returnfield = null;
            this.close();
        }
    }
    

    【讨论】:

      【解决方案4】:

      对于OnFormClosingFormClosingEventArgs.CloseReasonUserClosing要么是“X”按钮,要么是form.Close() 方法。 我的解决方案:

      //override the OnFormClosing event
              protected override void OnFormClosing(FormClosingEventArgs e)
              {
                  if (e.CloseReason == CloseReason.ApplicationExitCall)// the reason that you need
                      base.OnFormClosing(e);
                  else e.Cancel = true; // cancel if the close reason is not the expected one
              }
      //create a new method that allows to handle the close reasons
              public void closeForm(FormClosingEventArgs e)
              {
                  if (e.CloseReason == CloseReason.UserClosing) this.Close();
                  else e.Cancel = true;
              }
      
        //if you want to close the form or deny the X button action invoke closeForm method
          myForm.closeForm(new FormClosingEventArgs(CloseReason.ApplicationExitCall, false));
                                    //the reason that you want ↑
      

      在本例中,关闭 (X) 按钮不会关闭表单

      【讨论】:

        猜你喜欢
        • 2013-05-09
        • 2021-03-22
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        • 2017-09-04
        • 1970-01-01
        • 2020-05-23
        • 1970-01-01
        相关资源
        最近更新 更多