1. 程式人生 > >全局異常跟只能開啟一次程序,打開第二次將把該程序顯示最前

全局異常跟只能開啟一次程序,打開第二次將把該程序顯示最前

sage ace ttr 全局 imp cati 詳細 異常捕捉 creat

    static class SingleInstanceApplication
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr CreateMutex(IntPtr Attr, bool Own, string Name);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool ReleaseMutex(IntPtr hMutex);

        [DllImport(
"user32.dll")] public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab); const long ERROR_ALREADY_EXISTS = 183; public static void Run(Form frm) { string name = "SENSE_C2000"; IntPtr mutexHandle = CreateMutex(IntPtr.Zero, true, name);
long error = Marshal.GetLastWin32Error(); string pName = "SENSE-C2000";//要啟動的進程名稱,可以在任務管理器裏查看,一般是不帶.exe後綴的; Process[] temp = Process.GetProcessesByName(pName);//在所有已啟動的進程中查找需要的進程; if (error != ERROR_ALREADY_EXISTS) { Application.Run(frm); }
else { SwitchToThisWindow(temp[0].MainWindowHandle, true); // 激活,顯示在最前 //MessageBox.Show("您的程序已經在運行了,不能同時運行兩個實例!", "The Application has been running!"); LogHlep.WriteLog("重復登錄"); } ReleaseMutex(mutexHandle); } } static class Program { /// <summary> /// 應用程序的主入口點。 /// </summary> [STAThread] static void Main(string[] args = null) {        //全局異常捕捉 Application.ThreadException += Application_ThreadException; //UI線程異常 AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; //多線程異常 //args = new string[2];        //args[0] = "10001"; //if (args == null) //{ // args = new string[2]; // args[0] = "18231132"; //} Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new FrmMain(args)); SingleInstanceApplication.Run(new FrmMain(args)); }  //UI線程異常 static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { //WinformException.FrmBugReport.ShowBug(e.Exception); LogHlep.WriteLog("異常詳細信息:" + e.Exception.Message + "\r\n跟蹤:" + e.Exception.StackTrace); } //多線程異常 static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { //WinformException.FrmBugReport.ShowBug((Exception)e.ExceptionObject); Exception ex = (Exception)e.ExceptionObject; LogHlep.WriteLog("異常詳細信息:" + ex.Message + "\r\n跟蹤:" + ex.StackTrace); }

全局異常跟只能開啟一次程序,打開第二次將把該程序顯示最前