using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace HighWayAssemble
{
    static partial class Program
    {
        public static readonly log4net.ILog LogInfo = log4net.LogManager.GetLogger("RollingLogFileAppender"); //Logging 名字要在 App.config 中能找到
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private const int WS_SHOWNORMAL = 1;
        /// <summary> 
        /// 应用程序的主入口点。 
        /// </summary> 
        [STAThread]
        static void Main()
        {
            Process instance = RunningInstance();
            if (instance == null)
            {
                FramworkInit();
            }
            else
            {
                LogInfo.Fatal("已存在相同的运行实例！！！！！");

                HandleRunningInstance(instance);
            }
        }


        public static void Start()
        {
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FrmDisplayView());
        }
        /// <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)
                    {
                        LogInfo.FatalFormat("已存在：{0}", current.MainModule.FileName);

                        return process;
                    }
                }
            }
            return null;
        }

        /// <summary> 
        /// 显示已运行的程序。 
        /// </summary> 
        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //显示，可以注释掉 
            SetForegroundWindow(instance.MainWindowHandle);            //放到前端 
        }
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            LogInfo.FatalFormat("空间名：" + ex.Source + "；" + '\n' +
                                            "方法名：" + ex.TargetSite + '\n' +
                                            "故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' +
                                            "错误提示：" + ex.Message);
            Process.Start(Application.ExecutablePath);
            Process.GetCurrentProcess().Kill();
        }
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            LogInfo.FatalFormat("空间名：" + ex.Source + "；" + '\n' +
                                  "方法名：" + ex.TargetSite + '\n' +
                                  "故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' +
                                  "错误提示：" + ex.Message);
            Process.Start(Application.ExecutablePath);
            Process.GetCurrentProcess().Kill();
        }
    }

}