Bèlguesmi Sémah Bèlguesmi Sémah - 7 months ago 30
C# Question

Close form1 when closing form2 (from the red cross button)

I have two forms .. the form1 is a login form. so if the username and the password typed correctly .. the user will be directed to the form2 and hide form1..
The form2 contain a button "logout" for closing form2 and returning to form1 ..

this is the code for the button logout

private void logout_Click(object sender, EventArgs e)
foreach (Form OpenedForm in Application.OpenForms)
if (OpenedForm is Form1)

everything is ok with that .. but the only problem appears when the user clicks the red cross to exit the application directly without logging-out .. in this case the form1 (login) still hidden ..
Is there a solution to close form1 when closing form2 from the red cross ? thanks and sorry for my poor english


You can try to use FormClosing Event.

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    // close the first form...

This thread can help you to detect when the red cross was clicked...