mcbabo
mcbabo

Reputation: 23

Close Form when not clicking on it

I want to know if there is any event when you click on the rest of the screen and not the Windows Form the Form closes. Is it because of the ShowDialog()?

My Main Form is just with a notifyIcon and when I click it I call Form1.ShowDialog();

Main.cs:

private void ShowForm1(object sender, EventArgs e)
{
        form1.Left = Cursor.Position.X;
        form1.Top = Screen.PrimaryScreen.WorkingArea.Bottom - form1.Height;
        form1.ShowDialog();
}

Form1.cs:

private void Form1_Load(object sender, EventArgs e)
{
        label1.Text = "Test";
}

Upvotes: 1

Views: 334

Answers (2)

Flydog57
Flydog57

Reputation: 7111

You need to run the dialog box non-modally, not modally. Think about it, when you run it modally, the dialog box takes over the UI and plays games with mouse-clicks elsewhere, preventing you from running. You don't want it to be modal anyway.

I created a simple Windows form with a button that includes this handler to open a small AutoCloseDialog form I created (and populated with a few controls):

private void button1_Click(object sender, EventArgs e)
{
    var dlg = new AutoCloseDialog();
    dlg.Show(this);       //NOTE: Show(), not ShowDialog()
}

Then, in the AutoCloseDialog form, I wired up the Deactivate event. I did it in the designer (where this code is generated):

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

Finally, here is the handler for the Deactivate event.

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

I think this does what you are asking.

Upvotes: 1

Lucraft
Lucraft

Reputation: 73

Yes, you can create a similar function like this, which closes the Form if the Form lost focus (in Form1.cs)

public void Form_LostFocus(object sender, EventArgs e)
{
    Close();
}

and then you add the LoseFocus EventHandler (in Form1.Designer.cs):

this.LostFocus += new EventHandler(Form_LostFocus);

Upvotes: 0

Related Questions