WinForm中窗体的单例模式和单进程(存档)

来源:互联网 发布:iphonex怎么关掉软件 编辑:程序博客网 时间:2024/06/05 04:09
WinForm中窗体的单例模式和单进程

窗体单例模式的实现:

 

public static ChatForm newForm = null;

public static ChatForm GetInstance()
        {
            
if (newForm == null || newForm.IsDisposed == true)//newForm.IsDisposed == true必需,否则会出现“访问已释放资源”的异常
            {
                newForm 
= new ChatForm();
            }
            
else
            {
                newForm.Activate();
            }
            
return newForm;
        }

//调用:
ChatForm newForm = ChatForm.GetInstance();
newForm.Ipcon 
= Ip;
newForm.Show();

 

 

单进程的实现:

 


[STAThread]
        
static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(
false);
            
// get the name of our process
            string proc = Process.GetCurrentProcess().ProcessName;
            
// get the list of all processes by that name
            Process[] processes = Process.GetProcessesByName(proc);
            
// if there is more than one process
            if (processes.Length > 1)
            {
                MessageBox.Show(
"程序已经运行!");
                
return;
            }
            
else
                Application.Run(
new MainForm());
        }