开发者

Adding Form Closing Event In Code To Specific Object Instance?

开发者 https://www.devze.com 2023-03-05 06:09 出处:网络
Pretty simple what I want to do, just want to be able to run some code after a form is closed. Form1 f = new Form1();

Pretty simple what I want to do, just want to be able to run some code after a form is closed.

Form1 f = new Form1();
f.Show();
f.formClosing ... <- I just want to run code from th开发者_如何学运维is context once this form has been closed


{
    Form1 f = new Form1();
    f.FormClosed += new FormClosedEventHandler(f_FormClosed);
    f.Show();
}

void f_FormClosed(object sender, FormClosedEventArgs e)
{
    // Do stuff here
}


You can handle the Form.FormClosing event.

this.FormClosing += new FormClosingEventHandler(myForm_FormClosing);

void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
    //your code here
}


Form.FormClosing occurs before the form is closed. If you cancel this event, the form remains opened.

The right event to handle is Form.FormClosed :

form.FormClosed += 
     new Form.FormClosedEventHandler( Place the name of the handler method here ... );


Modern inline:

FormClosed += (s, a) => { /* your code here */ };


Recently I register my FORM exit handler this way (using .NET 4.8)

public partial class Form1:Form {
    public Form1() {
        this.FormClosed +=  Form1_Closing;
    }
    private void Form1_Closing(object sender, EventArgs e) {
        //Doing something while exit
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号