using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Web;
using Shell32;
using System.IO;
using System.Net;
using System.Text;

namespace US.Browser.IE
{
    static class Program
    {
        #region 添加用户信息

        /// <summary>
        /// 应用程序的主入口点
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //处理未处理的异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); //处理主线程ui异常
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); //所有错误的异常
            Process instance = _R(); //直接显示
            if (instance == null)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(StaticClass.Restart(Environment.CommandLine)); //Environment.CommandLine  args.Length > 0 ? StaticClass.Restart(Environment.CommandLine) : StaticClass.Restart("one")
            }
        }

        /// <summary>
        /// 出主线程ui的异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            BLL.USIE.Exception(sender, e.Exception);//错误处理
        }

        /// <summary>
        /// 主线程ui错误处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            BLL.USIE.Exception(sender, (Exception)e.ExceptionObject);//错误处理
        }

        /// <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>
        /// <returns></returns>
        private static Process _R()
        {
            Process currentproc = Process.GetCurrentProcess();
            Process[] processcollection = Process.GetProcessesByName(currentproc.ProcessName.Replace(".vshost", string.Empty));
            if (processcollection.Length >= 1)
            {
                foreach (Process process in processcollection)
                {
                    if (process.Id != currentproc.Id)
                    {
                        if (Assembly.GetExecutingAssembly().Location.Replace(@"/", @"\") == currentproc.MainModule.FileName)
                        {
                            if (BLL.USIE.isnet())
                            {
                                StaticClass._UST = "";
                                IntPtr formhwnd = BLL.WindowHWND.FindWindow(null, "云端");
                                BLL.WindowHWND.SetForegroundWindow(formhwnd); //将窗口放置最前端
                                BLL.WindowHWND.SwitchToThisWindow(formhwnd, true);
                                BLL.WindowHWND.ShowWindow(formhwnd, BLL.WindowHWND.SW_SHOW);  //调用api函数，正常显示窗口
                            }
                            return process;
                        }
                    }
                }
            }
            return null;
        }

        #endregion

        #region 无用区域

        ///// <summary>
        ///// 判断程序是否安装
        ///// </summary>
        ///// <returns></returns>
        //private static bool isIn()
        //{
        //    object _UDS; Microsoft.Win32.RegistryKey _UEK;
        //    Microsoft.Win32.RegistryKey _UKE = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");//获取所有安装的程序
        //    foreach (string USE in _UKE.GetSubKeyNames())
        //    {
        //        _UEK = _UKE.OpenSubKey(USE); _UDS = _UEK.GetValue("DisplayName"); if (_UDS != null)
        //        {
        //            if (_UDS.ToString().Contains("云端")) { return true; }
        //        }
        //    }
        //    return false;
        //}

        //[STAThread]
        //static void Main()
        //{
        //    Application.EnableVisualStyles();
        //    Application.SetCompatibleTextRenderingDefault(false);
        //    Application.Run(StaticClass.getInstance());
        //if (UD.TF) { int cfu = UD.CheckForUpdate().Count; }
        //}

        //if (UD.CFUTF())
        //{
        //    try
        //    {
        //        Application.Run(UpdateCue.NewUpCF());
        //    }
        //    catch { MessageBox.Show("文件损坏~！请重新下载！"); Environment.Exit(0); }
        //}
        //else
        //{
        //    Application.Run(StaticClass.getInstance());
        //}

        //Application.Run(StaticClass.getInstance());

        //MessageBox.Show(arg[0]);

        //private static Process RunningInstance()
        //{
        //    Process current = Process.GetCurrentProcess();
        //    MessageBox.Show(current.ProcessName);
        //    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;
        //}

        //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;
        //}
        //Process p = new Process();
        //p.StartInfo.UseShellExecute = false;
        ////AppDomain.CurrentDomain.BaseDirectory Application.StartupPath 两种获取本地地址方式
        //p.StartInfo.FileName = Application.StartupPath + "\\US.Browser.IE.Update.exe";
        //p.StartInfo.CreateNoWindow = true;
        //p.Start();
        //        //Environment.Exit(0);
        //        // Application.Exit(); 居然还会继续执行下面的内容
        //using (Mutex _UM = new Mutex(true, Application.ProductName, out _UTF))
        //{
        //    //MessageBox.Show(Environment.CommandLine);
        //    //Console.WriteLine("CommandLine: {0}", Environment.CommandLine);
        //    if (_UTF)
        //    {
        //        Application.SetCompatibleTextRenderingDefault(false);//美观等考虑，以及多语言字体的兼容问题
        //        //string[] arg = Environment.GetCommandLineArgs();//获取命令 第一个为文件名
        //        //Update.Update UD = new Update.Update();//加载下载页面
        //        //try
        //        //{
        //        //    if (UD.CFUTF()) { Application.Run(UpdateCue.NewUpCF()); return; }//启动下载更新
        //        //}
        //        //catch (Exception e) { }
        //        Application.Run(StaticClass.getI(Environment.CommandLine));//启动应用程序
        //    }
        //}

        #endregion
    }
}
