标签:
原文: C#中禁止程序多开
方法一、使用Mutex
bool createdNew; //返回是否赋予了使用线程的互斥体初始所属权
System.Threading.Mutex instance = new System.Threading.Mutex(true, "MutexName", out createdNew); //同步基元变量
if (createdNew) //赋予了线程初始所属权,也就是首次使用互斥体
{
Application.Run(new Form1()); /s/这句是系统自动写的
instance.ReleaseMutex();
}
else
{
MessageBox.Show("已经启动了一个程序,请先退出!","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
Application.Exit();
}
方法二、Process
测试函数:
private bool AppAlreadyRunning()
应用程序中直接判断: System.Diagnostics.Process[] pros =
{
System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess();
System.Diagnostics.Process[] allProcess = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process process in allProcess)
{
if (process.Id != curProcess.Id)
{
if (process.ProcessName == curProcess.ProcessName)
return true;
}
}
return false;
}
System.Diagnostics.Process.GetProcessesByName(
System.Diagnostics.Process.GetCurrentProcess().ProcessName);
if (pros.Length > 1)
{
Application.Exit();
return;
}
标签:
原文地址:http://www.cnblogs.com/lonelyxmas/p/4378726.html