WinForm的Program.cs处理:全局异常&单例运行

using System;
using System.Collections.Generic;
using System.Windows.Forms;

using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;

namespace StoreTradeSys
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                #region 处理全局异常
                //处理未捕获的异常  
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常  
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                //处理非UI线程异常  
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                #endregion

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                //Application.Run(new MainForm());

                //程序启动处理,同一时间只能运行一个应用
                Process theRunningInstance = GetTheRunningInstance();
                if (theRunningInstance == null)
                {
                    Application.Run(Singleton<MainForm>.Instance);
                }
                else
                {
                    HandleRunningInstance(theRunningInstance);
                }
            }
            catch (Exception ex)
            {
                string str = "";
                string strDateInfo = "出现应用程序未处理的异常:" + DateTime.Now.ToString() + "\r\n";

                if (ex != null)
                {
                    str = string.Format(strDateInfo + "异常类型:{0}\r\n异常消息:{1}\r\n异常信息:{2}\r\n",
                         ex.GetType().Name, ex.Message, ex.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}\r\n", ex);
                }


                Singleton<Log>.Instance.WriteLog(str, AppDomain.CurrentDomain.BaseDirectory + "Logs/");
                MessageBox.Show("发生致命错误,请及时联系作者!", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region 处理全局异常
        /// <summary>
        ///这就是我们要在发生未处理异常时处理的方法,我这是写出错详细信息到文本,如出错后弹出一个漂亮的出错提示窗体,给大家做个参考
        ///做法很多,可以是把出错详细信息记录到文本、数据库,发送出错邮件到作者信箱或出错后重新初始化等等
        ///这就是仁者见仁智者见智,大家自己做了。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {

            string str = "";
            string strDateInfo = "出现应用程序未处理的异常:" + DateTime.Now.ToString() + "\r\n";
            Exception error = e.Exception as 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}\r\n", e);
            }

            Singleton<Log>.Instance.WriteLog(str, AppDomain.CurrentDomain.BaseDirectory + "Logs/");
            MessageBox.Show("发生致命错误,请及时联系作者!", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = "";
            Exception error = e.ExceptionObject as Exception;
            string strDateInfo = "出现应用程序未处理的异常:" + DateTime.Now.ToString() + "\r\n";
            if (error != null)
            {
                str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆栈信息:{1}\r\n", error.Message, error.StackTrace);
            }
            else
            {
                str = string.Format("Application UnhandledError:{0}\r\n", e);
            }

            Singleton<Log>.Instance.WriteLog(str, AppDomain.CurrentDomain.BaseDirectory + "Logs/");
            MessageBox.Show("发生致命错误,请停止当前操作并及时联系作者!", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        #endregion

        #region 程序启动处理
        //不允许有两个程序同时启动
        public static Process GetTheRunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            //遍历正在有相同名字运行的例程
            foreach (Process process in processes)
            {
                //忽略现有的例程
                if (process.Id != current.Id)
                {
                    //确保例程从exe文件运行
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        //返回另一个例程实例
                        return process;
                    }
                }
            }

            //没有其它的例程,返回null
            return null;
        }

        public static void HandleRunningInstance(Process instance)
        {
            //0不可见但仍然运行,1居中,2最小化,3最大化
            int ws_shownormal = 1;

            //确保窗口没有被最小化或最大化
            ShowWindowAsync(instance.MainWindowHandle, ws_shownormal);

            //设置真实例程为foreground window
            SetForegroundWindow(instance.MainWindowHandle);
        }

        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hwnd, int cmdshow);

        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hwnd);
        #endregion
    }
}

阅读更多
想对作者说点什么? 我来说一句

全局异常捕捉 c#WinForm异常处理

2010年07月14日 46KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭