简体   繁体   English

我如何在按钮中放置表单关闭事件

[英]How can i put formclosing event in Button

I have a button called btnChallenge .我有一个名为btnChallenge的按钮。 The desired action is when it is clicked, the form cannot be closed.所需的操作是单击时无法关闭表单。

Here is what I have so far:这是我到目前为止所拥有的:

public void btnChallenge_Click(object sender, EventArgs e) { }

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // not sure on this if statement
    if (btnChallenge.Click)
    {
        e.Cancel = true;
    }
}

You could try it this way:你可以这样试试:

Declare a private variable inside a form:在表单中声明一个私有变量:

private bool _closedFromMyButton;

Then on FormClosing event check that property:然后在FormClosing事件上检查该属性:

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (_closedFromMyButton) // If closed from MyButton, don't do anything. let the form close.
        return;
    Hide(); // Hide the form (or not, it's up to you; this is useful if application has an icon in the tray)
    e.Cancel = true; // Cancel form closing
}

Then on some button click (if desired), put this code to close the form only from that button (or menuitem or toolbar button, etc.):然后单击某个按钮(如果需要),输入此代码以仅从该按钮(或菜单项或工具栏按钮等)关闭表单:

private void MyButtonClick(object sender, EventArgs e)
{
    _closedFromMyButton = true;
    Application.Exit(); // Or this.Close() if you just want to close the form.
}

You could define a variable which goes to true when you press the button and check on close if the variable is true您可以定义一个变量,当您按下按钮并检查关闭时该变量是否为真

eg例如

private bool btnClicked = false;
public void btnChallenge_Click(object sender, EventArgs e)
{
     btnClicked = true;
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if(btnClicked)
    {
        e.Cancel=true;
    }

}

You can just call the this.Close() method, this will call the Form1_FormClosing event:你可以只调用this.Close()方法,这将调用Form1_FormClosing事件:

public void btnChallenge_Click(object sender, EventArgs e)
{
    this.Close();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    //code here...
}

If you want to prevent the users by closing your form just after they have pressed some other button, then this code will help you.如果您想通过在用户按下其他按钮后立即关闭表单来阻止用户,那么此代码将对您有所帮助。

private bool close_state=false;    // hold the button state

// method to change the close_state by button click
private void Button1(object sender, EventArgs e)
{
    close_state = true;
    // if required you can toggle the close_state using an if statement
}

// Then on FormClosing event check that property:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (close_state) {// If the button is pressed
        e.Cancel = true; // Cancel form closing
    }
}

You may implement some other way to close the form....您可以实现一些其他方式来关闭表单....

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

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