C#编程中设置程序只可被运行一次的方法

2019-12-26 14:16:11于海丽

实现让程序只能打开一个实例(其他方法)

 

 
  1. //=====创建互斥体法:=====  bool blnIsRunning; 
  2. Mutex mutexApp = new Mutex(false, Assembly.GetExecutingAssembly().FullName, out blnIsRunning);  if (!blnIsRunning) 
  3. {  MessageBox.Show("程序已经运行!", "提示", 
  4. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);  return; 
  5. }    
  6.    
  7. //保证同时只有一个客户端在运行   System.Threading.Mutex mutexMyapplication = new System.Threading.Mutex(false, "OnePorcess.exe"); 
  8. if (!mutexMyapplication.WaitOne(100, false))  { 
  9. MessageBox.Show("程序" + Application.ProductName + "已经运行!", Application.ProductName,  MessageBoxButtons.OK, MessageBoxIcon.Error); 
  10. return;  } 
  11.    
  12. //=====判断进程法:(修改程序名字后依然能执行)=====  Process current = Process.GetCurrentProcess(); 
  13. Process[] processes = Process.GetProcessesByName(current.ProcessName);  foreach (Process process in processes) 
  14. {  if (process.Id != current.Id) 
  15. {  if (process.MainModule.FileName 
  16. == current.MainModule.FileName)  { 
  17. MessageBox.Show("程序已经运行!", Application.ProductName,  MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
  18. return;  } 
  19. }  }