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

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

阅读更多
文章标签: c# null user
个人分类: C#
上一篇C#里将其他共享目录映射为本地盘符的方法
下一篇ASP.NET常用函数
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭