简体   繁体   中英

How can i put formclosing event in Button

I have a button called 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:

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:

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....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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