全局异常跟只能开启一次程序,打开第二次将把该程序显示最前

    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 + "
跟踪:" + 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 + "
跟踪:" + ex.StackTrace);
        }
原文地址:https://www.cnblogs.com/lsgsanxiao/p/7472920.html