窗體單例模式的實現:
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());
}