ElGaMeD
ElGaMeD

Reputation: 13

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;
    }
}

Upvotes: 0

Views: 5287

Answers (4)

TCDutchman
TCDutchman

Reputation: 41

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

Upvotes: 1

kuma  DK
kuma DK

Reputation: 1861

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

Upvotes: 0

PatrickSchiefer
PatrickSchiefer

Reputation: 161

You could define a variable which goes to true when you press the button and check on close if the variable is true

e.g.

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;
    }

}

Upvotes: 1

Jure
Jure

Reputation: 1176

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

Upvotes: 2

Related Questions