線程異常,而進程不死 | 每次只打開一個桌面程序

using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Configuration;
using Jd.Club.Extension;
using System.Security.Permissions;

namespace Jd.Club.WinActivityProcess
{
    static class Program
    {
        /// <summary>
        /// 該函數設置由不同線程產生的窗口的顯示狀態。
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="cmdShow">指定窗口如何顯示。查看允許值列表,請查閱ShowWlndow函數的說明部分。</param>
        /// <returns>如果函數原來可見,返回值爲非零;如果函數原來被隱藏,返回值爲零。</returns>
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        /// <summary>
        /// 該函數將創建指定窗口的線程設置到前臺,並且激活該窗口。鍵盤輸入轉向該窗口,併爲用戶改各種可視的記號。系統給創建前臺窗口的線程分配的權限稍高於其他線程。
        /// </summary>
        /// <param name="hWnd">將被激活並被調入前臺的窗口句柄。</param>
        /// <returns>如果窗口設入了前臺,返回值爲非零;如果窗口未被設入前臺,返回值爲零。</returns>
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private const int WS_SHOWNORMAL = 1;

        /// <summary>
        /// 應用程序的主入口點。
        /// </summary>
        [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
        [STAThread]
        static void Main()
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
           
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Process instance = RunningInstance();
            if (instance == null)
            {
                Application.Run(new WindowsActivityProcess());
            }
            else
            {
                HandleRunningInstance(instance);
            }
        }

        /// <summary>
        /// 獲取正在運行的實例,沒有運行的實例返回null;
        /// </summary>
        public 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;
        }

        /// <summary>
        /// 顯示已運行的程序。
        /// </summary>
        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //顯示,可以註釋掉
            SetForegroundWindow(instance.MainWindowHandle);            //放到前端
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleUnhandledException(e.ExceptionObject);
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleUnhandledException(e.Exception);
        }

        private static void HandleUnhandledException(Object o)
        {
            try
            {
                string mailTo = ConfigurationManager.AppSettings["MailTo"];
                if (!string.IsNullOrEmpty(mailTo))
                {
                    string[] mails = mailTo.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string mail in mails)
                    {
                        MailHelper.Send(string.Format("活動評論處理異常,時間:{0}", DateTime.Now), o.ToString(), mail);
                    }
                }
            }
            finally
            {
                Environment.Exit(0);
            }
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章