日期:2014-05-18  浏览次数:20893 次

急救 如何保证打开窗体的唯一性?
这是我要打开窗体的二句代码,我想实现点击toolStripMenuItem1时,如果窗体没有打开,那就打开,如果已经打开,再点击的时候什么也不做? 谢谢各位?
private void toolStripMenuItem1_Click(object sender, EventArgs e)
  {
  Form f2 = new Form();
  f2.Show();
  }


 

------解决方案--------------------
C# code
      Form f2 = new Form(); 
        private void button1_Click(object sender, EventArgs e)
        {    
            f2.Show();
        }

------解决方案--------------------
C# code

        Form f2;
        private void toolStripMenuItem1_Click(object sender, EventArgs e) 
        { 
            if(!f2.Created)
            {
               f2=new Form();
               f2.Show();
            }
        }

------解决方案--------------------
单件模式

C# code

public class Form2()
{
  private Form2 f2;
  private Form2()
  {
     //构造函数声明为私有
  }
  public static Form2 GetForm2()
  {
    if(this.f2==null)
    {
      this.f2=new Form2();
    }
    return this.f2;
  }
}

------解决方案--------------------
private void toolStripMenuItem1_Click(object sender, EventArgs e) 


if(f2==null||f2.Disposed)
{Form f2 = new Form(); }
f2.Show(); 
}
------解决方案--------------------
参考如下:

C# code

private Form f2 = null;
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    if (f2 == null || f2.IsDisposed)
    {
        f2 = new Form();
    }
    f2.Show();
}

------解决方案--------------------
Form f2 = null;
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
if (f2 == null || f2.IsDisposed)
{
f2 = new Form();
}
f2.Show();



------解决方案--------------------
如果是MDI窗体可参考下
private void toolStripMenuItem1_Click(object sender, EventArgs e) 

Form f2 = new Form(); 
f2.Show(); 
foreach (Form form in this.MdiChildren)
{ if (form is Form)
{
form.Focus();
return;
}
}
Form f2 = new Form();
f2.MdiParent = this;
f2.Show();

 }