winform

static void Main()
        {
            try
            {
                //處理未捕獲的異常   
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //處理UI線程異常   
                Application.ThreadException += Application_ThreadException;
                //處理非UI線程異常   
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                //0106add  一次打開一個應用程序
                Process instance = RunningInstance();
                if (instance != null)
                {
                    if (instance.MainWindowHandle.ToInt32() == 0) //是否托盤化
                    {
                        MessageBox.Show("程序已打開並托盤化");
                        return;
                    }
                    //1.2 已經有一個實例在運行
                    HandleRunningInstance(instance);
                    return;
                }
                ConfigTool.Path = ParamCache.formPath + "\\Config\\config.xml";
                ConfigTool.GetConfigDic();

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                BonusSkins.Register();
                LoginForm login = new LoginForm();
                login.ShowDialog();
                if (login.DialogResult == DialogResult.OK)
                {
                    login.Dispose();
                    Application.Run(new MainForm());
                }
            }
            catch (Exception ex)
            {
                var strDateInfo = "出現應用程序未處理的異常:" + DateTime.Now + "\r\n";

                var str = string.Format(strDateInfo + "異常類型:{0}\r\n異常消息:{1}\r\n異常信息:{2}\r\n",
                                           ex.GetType().Name, ex.Message, ex.StackTrace);

                LogTool.Info(str);
                MessageBox.Show("發生錯誤,請查看程序日誌!", "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(0);
            }
        }

        #region 確保程序只運行一個實例
        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;
        }
        //3.已經有了就把它激活,並將其窗口放置最前端
        private static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, 1); //調用api函數,正常顯示窗口
            SetForegroundWindow(instance.MainWindowHandle); //將窗口放置最前端
        }
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);
        #endregion

        #region 錯誤處理
        /// <summary>
        ///錯誤彈窗
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str;
            var strDateInfo = "出現應用程序未處理的異常:" + DateTime.Now + "\r\n";
            var error = e.Exception;
            if (error != null)
            {
                str = string.Format(strDateInfo + "異常類型:{0}\r\n異常消息:{1}\r\n異常信息:{2}\r\n",
                     error.GetType().Name, error.Message, error.StackTrace);
            }
            else
            {
                str = string.Format("應用程序線程錯誤:{0}", e);
            }

            LogTool.Info(str);
            MessageBox.Show("發生錯誤,請查看程序日誌!", "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Environment.Exit(0);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var error = e.ExceptionObject as Exception;
            var strDateInfo = "出現應用程序未處理的異常:" + DateTime.Now + "\r\n";
            var str = error != null ? string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆棧信息:{1}", error.Message, error.StackTrace) : string.Format("Application UnhandledError:{0}", e);

            LogTool.Info(str);
            MessageBox.Show("發生錯誤,請查看程序日誌!", "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Environment.Exit(0);
        }
        #endregion

  

/// <summary>  
        /// 修改程序在註冊表中的鍵值  
        /// </summary>  
        /// <param name="flag">1:開機啓動</param>  
        private void StartUp(string flag)
        {
            string path = Application.StartupPath;
            string keyName = path.Substring(path.LastIndexOf("\\") + 1);
            Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

            if (flag.Equals("1"))
            {
                if (Rkey == null)
                {
                    Rkey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                }
                Rkey.SetValue(keyName, path + @"\KBDMtrlSystemForm.exe");
            }
            else
            {
                if (Rkey != null)
                {
                    Rkey.DeleteValue(keyName, false);
                }
            }
        }
相關文章
相關標籤/搜索