'How do I trigger a form to close when it loses focus
I have two forms, form1 and form2. form1 has a button that when clicked opens form2 center screen over form1. form2 is smaller than form1 (on purpose). If the click event is triggered and form2 is open, then the user clicks on form1, form2 falls to the background as most programs in windows do.
What I want: is when form2 is open, and the user clicks on something else, form2 closes.
I've tried (on form2):
private void formLostFocus (object sender, System.EventArgs e)
{
this.Close();
}
Solution 1:[1]
Try this code:
private void Form2_Deactivate(object sender, EventArgs e)
{
this.Close();
}
And subscribe to the Deactivate
event
this.Deactivate += new System.EventHandler(this.Form2_Deactivate);
Solution 2:[2]
Use this code:
This is for the event that will open form2
private void button1_Click(object sender, EventArgs e)
{
Test.Form2 frm = new Test.Form2();
frm.TopMost = true;
frm.Show();
}
Use the Deactivate in form2 that will close the form when u click outside the form and make sure to use the TopMost = true; when opening the form.
private void Form2_Deactivate(object sender, EventArgs e)
{
this.Close();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nick stands with Ukraine |
Solution 2 |