使用程序列舉的方式,實作單個執行個體的WinForm
[STAThread]
static void Main()
... {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//在這裡可以修改為需要的程序名稱。
if (!HasInstance("SingleInstance"))
...{
Application.Run(new Form1());
}
else
...{
MessageBox.Show("Exist one Instance");
Application.Exit();
}
}
// 使用程序列舉,看看是否已經存在相同名稱的程序
private static bool HasInstance( string name)
... {
Process[] prces = Process.GetProcesses();
int count = 0;
foreach (Process pro in prces)
...{
if(pro.ProcessName==name)
...{
count++;
}
}
if(count>1)
return true;
else
return false;
}