如何在Button中放置formclosing事件

时间:2015-06-22 15:10:51

标签: c# winforms

我有一个名为btnChallenge的按钮。所需的操作是单击它时,表单无法关闭。

这是我到目前为止所做的:

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

4 个答案:

答案 0 :(得分:2)

你可以这样试试:

在表单中声明一个私有变量:

private bool _closedFromMyButton;

然后在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
}

然后在某个按钮上单击(如果需要),将此代码设置为仅从该按钮(或menuitem或工具栏按钮等)关闭表单:

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

答案 1 :(得分:1)

您可以定义一个变量,当您按下按钮时该变量变为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;
    }

}

答案 2 :(得分:1)

您可以调用this.Close()方法,这会调用Form1_FormClosing事件:

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

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

答案 3 :(得分:0)

如果您想在按下其他按钮后关闭表单来阻止用户,那么此代码将对您有所帮助。

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

您可以采用其他方式关闭表单....

相关问题