Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c# - 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";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...