如何检测系统是否已经运行了相同的程序

来源:互联网 发布:守望先锋配置测试软件 编辑:程序博客网 时间:2024/04/30 18:21

using System;
  using System.Xml;
  using System.ComponentModel ;
  using System.Windows.Forms;
  using System.Diagnostics;
  using System.Runtime;
  using System.Reflection;
  using System.Runtime.InteropServices;
  [STAThread]
   static void Main() //主程序运行
   {
   Process intance=RunningIntance(); //调用检查函数
   if(intance==null) //不存在相同的程序
   {
   Application.Run(new frmMain());
   }
   else //存在相同的程序
   {
   HandleRunningInstance(intance);
   }
  }
  private static Process RunningIntance()
   {
   Process currentProcess=Process.GetCurrentProcess();
   Process [] processCollection=Process.GetProcessesByName(currentProcess.ProcessName);
   foreach(Process p in processCollection)
   {
   if(p.Id!=currentProcess.Id) //检查ID是否相同
   {
   //检查运行文件路径是否相同
   if(Assembly.GetExecutingAssembly().Location.Replace("/","/")==currentProcess.MainModule.FileName)
   return currentProcess;
   }
   }
   return null;
   }
   private static void HandleRunningInstance(Process instance)
   {
   MessageBox.Show("该应用系统(PSP)已经在运行!","提示信息",MessageBoxButtons.OK,MessageBoxIcon.Information);
   ShowWindowAsync(instance.MainWindowHandle,1); //调用api函数,正常显示窗口
   SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端。
  
   }
   [DllImport("User32.dll")]
   private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
   [DllImport("User32.dll")]
   private static extern bool SetForegroundWindow(System.IntPtr hWnd);

原创粉丝点击