CSDN博客

img herman_chow

保证C#应用程序只有一个实例在运行

发表于2004/7/7 15:30:00  941人阅读

  [STAThread]
  static void Main()
  {
   Process instance = RunningInstance();
   if (instance == null)
   {
    Application.Run(new mainFrm());
   }
   else
   {
    //MessageBox.Show("此程序已经启动!");
    HandleRunningInstance(instance);
   }  
  }

  [DllImport("User32.dll")]
  private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

  [DllImport("User32.dll")]
  private static extern bool SetForegroundWindow(IntPtr hWnd);

  private const int WS_SHOWNORMAL = 1;

  private static Process RunningInstance()
  {
   Process current = Process.GetCurrentProcess();
   Process[] processes = Process.GetProcessesByName(current.ProcessName);

   foreach (Process process in processes)
   {
    if (process.Id!=current.Id)
    {
     if (Assembly.GetExecutingAssembly().Location.Replace("/", "//")==current.MainModule.FileName)
     {
      return process;
     }
    }
   }

   return null;
  }

  private static void HandleRunningInstance(Process instance)
  {
   ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);

   SetForegroundWindow(instance.MainWindowHandle);
  }

0 0

相关博文

我的热门文章

img
取 消
img