c# 只允许一个实例运行

时间:2023-01-05 11:17:52
1.单件模式,Singleton,应用程序只能允许一个实例在运行.这是最好的解决方法
2.查询系统进程里是不是已经运行.
private void Form1_Load(object sender, EventArgs e)
{
string fileName = Path.GetFileNameWithoutExtension(Application.ExecutablePath);
Process[] processes = Process.GetProcessesByName(fileName);
Process currentProcess = Process.GetCurrentProcess();
foreach (Process p in processes)
{
if (p.Id != currentProcess.Id)
{
p.Kill();
}
}
}