简体   繁体   English

使用 X 或创建按钮关闭表单

[英]Closing Form with X or created button

I have a Log In form and I need to know if user pressed the X button on form or the button that takes him to the new form.我有一个登录表单,我需要知道用户是否按下了表单上的 X 按钮或将他带到新表单的按钮。 If user closed the program with Alt+F4 or X button the program must be closed.如果用户使用 Alt+F4 或 X 按钮关闭程序,则必须关闭程序。

I was trying with FormClosing event to check whether user pressed X or login.我正在尝试使用 FormClosing 事件来检查用户是否按下 X 或登录。

 private void LogIn_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (string.Equals((sender as Button).Name, @"loginButton"))
        {
            //some code
        }
        else
        {
            Close();
        }
    }

The FormClosing event handler receives a FormClosingEventArgs argument that contains the property CloseReason , but in your context this is not enough. FormClosing事件处理程序接收包含属性CloseReasonFormClosingEventArgs参数,但在您的上下文中,这还不够。
Indeed, in both cases (ALT+F4/X-Click or ButtonClick) the argument will contain a CloseReason equal to UserClosing .实际上,在这两种情况下(ALT + F4 / X-点击或ButtonClick)的参数将包含一个CloseReason等于UserClosing。

I suggest you a simple workaround.我建议你一个简单的解决方法。 In your button click handler (where you should call the close action on the form, not on the formclosing event handler itself), add something to the Tag property of the form like so:在您的按钮单击处理程序中(您应该在表单上调用关闭操作,而不是在表单关闭事件处理程序本身)中,向表单的 Tag 属性添加一些内容,如下所示:

private void Button1_Click(object sender, EventArgs e)
{
    this.Tag = "ClosedByUser";
    this.Close();
}

now in the FormClosing event handler is simple to check this property现在在 FormClosing 事件处理程序中很容易检查这个属性

private void LogIn_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.Tag != null)
    {
        // Button clicked
    }
    else
    {
        // other reasons
        // Dp not call Close here, you are already closing 
        // if you don't set e.Cancel = true;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM