我有一个表单,我想获得与下面代码中所述相同表单的实例。我有一个按钮:每次按下此按钮,如果创建了新表单,我希望它专注于该窗口,如果没有,我想创建一个新表单。
我设法创建了一个新表单,但如果我想专注于它,代码不起作用,任何想法?
private void btn_Click(object sender, EventArgs e)
{
if (opened == false)
{
Text = "form1";
var form = new myformapp();
form.Show();
opened = true;
form.Text = "form2";
}
else
{
if (Application.OpenForms[1].Focused)
{
Application.OpenForms[0].BringToFront();
Application.OpenForms[0].Focus();
}
if (Application.OpenForms[0].Focused)
{
Application.OpenForms[1].BringToFront();
Application.OpenForms[1].Focus();
}
}
}
答案 0 :(得分:1)
如果我正确理解您要执行的操作,则可以使用打开的表单保留静态列表。每次打开表单实例时,都会将其添加到列表中,每次关闭时都将其删除。按下按钮时,您可以检查列表的大小。如果为1,则创建一个新表单,打开它并将焦点设置在其上。如果大小已经是2,则在List中查找与执行click事件的实例不同的实例。代码可能是这样的:
private static List<Form1> openForms = new List<Form1>();
private void button1_Click(object sender, EventArgs e)
{
Form1 frm = null;
if (openForms.Count == 2)
{
foreach (Form1 aForm in openForms)
if (aForm != this)
{
frm = aForm;
break;
}
}
else
{
frm = new Form1();
frm.Show();
}
frm.Focus();
}
private void Form1_Load(object sender, EventArgs e)
{
openForms.Add(this);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
openForms.Remove(this);
}
答案 1 :(得分:1)
您可以尝试缩短代码,而无需在此示例中引入更多变量:
void button1_Click(object sender, EventArgs e) {
bool found = false;
for (int i = 0; i < Application.OpenForms.Count; ++i) {
if (Application.OpenForms[i].GetType() == typeof(myformapp) &&
Application.OpenForms[i] != this) {
Application.OpenForms[i].Select();
found = true;
}
}
if (!found) {
myformapp form = new myformapp();
form.Show();
}
}
更新了Francesco Baruchelli的评论代码。