Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
So I have a main form called 'form1' from which I can click a button to show another form called 'form2'. How can I run some code in 'form1' when the event of 'form2' closing occurs?
Posted
Comments
Sergey Alexandrovich Kryukov 9-Nov-12 0:58am    
What's so special about this case? Why this is a problem? Do you know how handle events or override methods? Did you see MSDN help on forms? What did you try?
--SA
FourCrate 9-Nov-12 18:59pm    
Not really, I've been searching a lot but couldn't find anything. I guess I'm not searching the right thing that will solve the problem. I was too stumped to even try it, but the below example helps and I'll use that to find out more.

1 solution

Take a look:
C#
form2.FormClosed += (sender, eventArgs) => {
    // some code
};
or
C#
form2.FormClosing += (sender, eventArgs) => {
    Form senderForm = (Form)sender; // will always cast to this type, no need to check up, see below
    // some code
    // but you can also prevent closing of the form based of some condition:
    if (shouldNotCloseIt /* whatever */ && eventArgs.CloseReason == UserClosing) {
        eventArgs.Cancel = true;
        senderForm.Hide(); // typical use of it; actually senderForm == form2, see above
    } // if
    // some more code
}


Please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosed.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.formclosingeventargs.closereason.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.closereason.aspx[^].

—SA
 
Share this answer
 
v3
Comments
Rahul Rajat Singh 9-Nov-12 1:19am    
oh I was about to write the same, i even wrote all the code but you beat me to it :(

nevertheless, +5.
Sergey Alexandrovich Kryukov 9-Nov-12 1:23am    
Thank you, Rahul.
--SA
FourCrate 9-Nov-12 18:57pm    
Many thanks, it worked
Sergey Alexandrovich Kryukov 9-Nov-12 19:12pm    
Great. You are welcome.
Good luck, call again.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900