简体   繁体   中英

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

Try please this code

private void Form2_Deactivate(object sender, EventArgs e)
        {
            this.Close();
        }

And subscribe to Deacticate event

this.Deactivate += new System.EventHandler(this.Form2_Deactivate);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM