所有WinForm表单的单个实例

时间:2012-10-19 05:49:12

标签: c# winforms

我正在开发一个C#Windows Forms应用程序。我希望有一个所有表格的单个实例。

因此,当用户点击“联系人”按钮时,例如,两次,而不是有两个联系表单,我会将单个实例联系表单放在前面。

我怎样才能做到这一点?

7 个答案:

答案 0 :(得分:8)

在使用Application.OpenForms

创建和显示表单之前,请检查表单是否存在于打开表单的集合中
if (System.Windows.Forms.Application.OpenForms["Form1"] as Form1 != null)
       MessageBox.Show("Form1 is opened");
 else
       MessageBox.Show("Form1 is not opened");

答案 1 :(得分:3)

public static Form GetOpenedForm<T>() where T: Form {
    foreach (Form openForm in Application.OpenForms) {
        if (openForm.GetType() == typeof(T)) {
            return openForm;
        }
    }
    return null;
}

在您的代码中,您可以在其中创建ContactForm

ContactForm form = (ContactForm) GetOpenedForm<ContactForm>();
if (form == null) {
    form = new ContactForm();
    form.Show();
} else {
    form.Select();
}

答案 2 :(得分:2)

简单:

Form fc = Application.OpenForms["Form1"];
            if (fc != null)
            {
                fc.Focus();
            }
            else
            {
                Form1 f1 = new Form1();
                f1.Show();
            }

答案 3 :(得分:1)

试试这个组合

首先与全球对象建立联系

private ContactForm contactForm;

然后是你的联系按钮处理程序:

private void contactButton_Click(object sender, EventArgs e)
{
    if (contactForm == null)
    {
       contactForm = new ContactForm();
       contactForm.FormClosing += new FormClosingEventHandler(contactForm_FormClosing);
    }
    contactForm.Show();
}

然后处理ContactForm的FormClosing事件以隐藏它而不是关闭它:

private void contactForm_FormClosing(object sender, FormClosingEventArgs e)
{
    contactForm.Hide();
    e.Cancel = true;
}

或者,如果您希望关闭联系表单,并在下次打开新表单,请改为处理FormClosed:

private void contactForm_FormClosed(object sender, FormClosedEventArgs e)
{
    contactForm = null;
}

然后,下次单击该按钮时,将捕获null if子句,并将表单设置为新实例并打开。

答案 4 :(得分:1)

Form2 form2 = null;
private void button1_Click(object sender, EventArgs e)
{
 bool isFormExists = false;
 foreach (Form openForm in Application.OpenForms)
 {
  if (openForm == form2 && openForm!=null)
  {
   openForm.Focus();
   isFormExists = true;
   break;
  }
 }

 if (!isFormExists)
 {
  form2 = new Form2();
  form2.Show();
 }
}

答案 5 :(得分:1)

点击广告后,您可以停用contactButton并打开contactForm -

private void contactButton_Click(object sender, EventArgs e)
{
  contactButton.Enabled=false;
  //code to open the contactForm
}

关闭contactForm后,您可以重新启用按钮 -

contactButton.Enabled=true;

答案 6 :(得分:1)

我会回答奥蒂尔的回答。您还可以添加一个WindowState,因为如果表单最小化,它将不会显示。 this回答可用于获取恢复方法。

ContactForm form = (ContactForm) GetOpenedForm<ContactForm>();
if (form == null) {
    form = new ContactForm();
    form.Show();
} else {
    //use this (if you want it to be restored to normal and focused)
    //no need of extension method
    //form.WindowState = FormWindowState.Normal;
    //form.Select();

    //or use this if you want it to be restored as previous state and focused
    //You need a Restore extension method that can be found in the link above
    form.Focus();
    form.Restore();
}