I a form than I can open it also by pressing F1 and clicking so in this code first I check if the form has been opened or not.if was opened I just want to bring it to front. my problem is it wont bring in front by pressing F1 or clicking ToolStripMenuItem if i open it befor.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
Form2 form2;
form2 = new Form2();
if (e.KeyCode.ToString() == "F1" &&开发者_开发知识库; Application.OpenForms.OfType<Form2>().Count() <= 0)
// the user pressed the F1 key
form2.Show();
else
{
form2.TopMost = true;
form2.BringToFront();
form2.Focus();
form2.TopMost = false;
}
}
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 form2;
form2 = new Form2();
if (Application.OpenForms.OfType<Form2>().Count() <= 0)
form2.Show();
else
{
form2.TopMost = true;
form2.BringToFront();
form2.Focus();
form2.TopMost = false;
}
}
It doesn't work because you forgot to call form2.Show() in the else clause. The code is wrong, you don't want to create a new instance of Form2 if one already exists. Also, there's a bug in Winforms that makes Application.OpenForms lose track of form instances.
Best thing to do is to explicitly keep track of the lifetime of the form with its FormClosed event handler so you don't have to find it back later:
Form2 form2;
private void showForm2() {
if (form2 == null) {
form2 = new Form2();
form2.FormClosed += delegate { form2 = null; };
}
form2.Show();
form2.Focus();
}
Call showForm2 from your event handlers.
Just call form2.Show()
and BringToFront
. You should declare the `new Form2()' once though.
private Form2 form2;
private void ShowForm2()
{
if (form2 == null)
{
form2 = new Form2();
form2.FormClosed += delegate { form2 = null; };
}
form2.Show();
form2.BringToFront();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
ShowForm2();
}
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowForm2();
}
From Hans' code, I added the delegate to handle null problem on closing the form and opening it again.
精彩评论