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());
        }
發佈了51 篇原創文章 · 獲贊 6 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章