C# 同一窗体一次只打开一个实列(单态)

来源:互联网 发布:马思纯演技知乎 编辑:程序博客网 时间:2024/05/23 13:04


在窗体中加入如下代码
private static 窗体 instance = null;
//添加一个属性
public static 窗体 Instance
{
     
set{
     }
     
get{
         
if(instance == null){
             
new 窗体();
         }
         
return instance;
     }
}
在窗体的构造函数中加入如下代码
instance = this;
创建窗体Closed事件
private void 窗体_FormClosed(object sender, FormClosedEventArgs e)
{
    instance 
= null;
}

使用方法:
在要调用该窗体的地方加入如下代码
窗体 myfrm = 窗体.Instance; 
myfrm.Show();
myfrm.Activate();