This is herman's Blog!

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

  [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);
  }

posted on 2005-05-16 18:14  This is herman's Blog!  阅读(321)  评论(0)    收藏  举报