C#表单X按钮被点击

7
如何判断表单是通过点击 X 按钮关闭还是通过 (this.Close()) 关闭的?

这个比写代码更简单。 - user1937254
4个回答

23

该表单具有事件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,然后返回。从外部来看,我知道当这个表单返回null时,我不需要做任何操作。但是当通过点击X关闭表单时,该字段不为null,导致外部代码崩溃。 - fm_strategy

3

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

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


1
如果您想将返回字段设置为null,就像在表单中单击“取消”时那样:
private void Form1_FormClosing( object sender, FormClosingEventArgs e )
{
    if ( e.CloseReason == CloseReason.UserClosing )
    {
        returnfield = null;
        this.close();
    }
}

0

对于 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)按钮无法关闭表单。

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