C#启动程序时检测运行多个实例
作者:C/S框架网  发布日期:2013-01-08 14:30:46
  C#启动程序时检测运行多个实例


C# Code:

static class Program
{
   /// <summary>
   /// The main entry point for the application.
   /// </summary>
   [STAThread]
   static void Main()
   {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.ThreadException = new ThreadExceptionEventHandler(Application_ThreadException);//捕获系统所产生的异常。
      Application.ThreadExit = new EventHandler(Application_ThreadExit);
      
      #region 检查程序是否运行多实例
      if (Program.IsRunInstance())//检查程序是否运行多实例
      {
         Msg.Warning("系统已经启动!");
         Application.ExitThread();
         Application.Exit();
         return;
      }
      #endregion
      
      Application.Run(new frmMonitor());//运行主窗体
   }
   
   static void Application_ThreadExit(object sender, EventArgs e)
   {
      if (mutex != null)
      {
         mutex.ReleaseMutex();
         mutex = null;
      }
   }
   
   private static Mutex mutex = null;
   
   /// <summary>
   ///检查程序是否运行多实例
   /// </summary>
   public static bool IsRunInstance()
   {
      mutex = new Mutex(false, "指纹考勤系统");
      if (!mutex.WaitOne(0, false))//如果返回false则mutex已经被另一个线程所拥有
      {
         mutex.Close();
         mutex = null;
         return true;
      }
      return false;
   }
   
   private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
   {
      MonitorLog.AddLog(e.Exception.Message);//程序未知错误,写入日志
   }
   
}

//来源:C/S框架网(www.csframework.com) QQ:1980854898


上一篇 下一篇