C#程序多用户只启动一个进程的方法[转载]

时间:2022-06-01 19:10:22

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://greenlandy.blogbus.com/logs/14388828.html

Code Snippet
  1. [STAThread]
  2.      private static void Main()
  3.      {
  4.          Application.EnableVisualStyles();
  5.          Application.SetCompatibleTextRenderingDefault(false);
  6.          var wb = new Form1();
  7.          Process current = Process.GetCurrentProcess();
  8.          bool newinstance = true;
  9.          Process[] processes = Process.GetProcessesByName(current.ProcessName);
  10.  
  11.          //?历正在有相同名字??的例程  
  12.          foreach (Process process in processes)
  13.          {
  14.              //忽略现有的例程  
  15.              if (process.Id != current.Id)
  16.              {
  17.                  //确保例程从EXE文件??  
  18.                  if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
  19.                  {
  20.                      //?回另一个例程实例  
  21.                      current = process;
  22.                      newinstance = false;
  23.                      break;
  24.                  }
  25.              }
  26.          }
  27.          if (newinstance)
  28.          {
  29.              Application.Run(wb);
  30.          }
  31.          else
  32.          {
  33.              ShowWindowAsync(current.MainWindowHandle, 1);
  34.  
  35.              //?置真实例程为foreground   window  
  36.              SetForegroundWindow(current.MainWindowHandle);
  37.          }
  38.      }

引入这两个API函数

Code Snippet
  1. [DllImport("User32.dll")]
  2. private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
  3.  
  4. [DllImport("User32.dll")]
  5. private static extern bool SetForegroundWindow(IntPtr hWnd);