Program.cs 14.2 KB
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using Comm;
using BizFacade;
using System.Runtime.InteropServices;
using log4net;
using System.Reflection;

namespace App
{
    public static class Program
    {
        #region 
        ///// <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);

        //[DllImport("user32.dll", CharSet = CharSet.Auto)]
        //static extern bool ShowWindow(IntPtr hwnd, int state);

        //[DllImport("user32.dll", EntryPoint = "FindWindowA")]
        //public static extern IntPtr FindWindowA(string lp1, string lp2);
        #endregion

        static LoginManager _loginManager;
        public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public static bool IsDebug=false;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] Args)
        {
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false); 
            var largs = new List<string>(Args);
            if (largs.Contains("debug"))
                IsDebug = true;

            System.Environment.CurrentDirectory = Application.StartupPath;


            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadExcetption);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrencyDomain_UnhandledException);

            string name = Process.GetCurrentProcess().ProcessName;
            int id = Process.GetCurrentProcess().Id;
            Process[] prc = Process.GetProcesses();
            foreach (Process pr in prc)
            {
                if ((name == pr.ProcessName) && (pr.Id != id))
                {
                    //IntPtr inPTR=FindWindowA(null, "Contamination Explorer");
                    MessageBox.Show("该程序已打开,不能重复打开!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);   
                    //ShowWindowAsync(inPTR, 3); //显示,可以注释掉 
                    //SetForegroundWindow(inPTR);            //放到前端 
                    Application.Exit();   
                    return;
                }
            }    

            _loginManager = new LoginManager();
            /**
             * 自动以管理员身份打开软件
             */
            //获得当前登录的Windows用户标示 
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            //创建Windows用户主题 
            Application.EnableVisualStyles();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);

            bool isAdmin = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);

            //调试时使用非管理员才可登陆进系统,因此调试时把isAdmin设置为true
            //isAdmin = true;

            //判断当前登录用户是否为管理员
            if (isAdmin)
            {
                //如果是管理员,则直接运行 
                //Application.EnableVisualStyles();

                if (!_loginManager.ShowLoginForm(_loginManager))
                {
                    return;
                }
               

                if (!_loginManager.ShowMidForm(_loginManager, null))
                {
                    return;
                }
                try
                {
                    Application.Run();
                }
                catch (Exception e)
                {
                    LOGGER.Warn(e.StackTrace);
                    System.Environment.Exit(System.Environment.ExitCode); 
                }
                }
            else
            {
                //创建启动对象 
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                //设置运行文件
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                //设置启动参数 
                startInfo.Arguments = String.Join(" ", Args);
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                startInfo.UseShellExecute = false;
                //如果不是管理员,则启动UAC 
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }catch(Exception e){
                    LOGGER.Error(e);
                }
                //退出 System.Windows.Forms.Application.Exit(); 
            }     
        }

        static void CurrencyDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LogUnhandledException(e.ExceptionObject);
        }

        static void Application_ThreadExcetption(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            LogUnhandledException(e.Exception);
        }

        static void LogUnhandledException(object exceptionobj)
        {
            //这里可以进一步地写日志
            LOGGER.Info(exceptionobj.ToString());
        }
    }

    public sealed class LoginManager
    {
        public bool IsExit = false;

        public bool ShowLoginForm(LoginManager loginManager)
        {
            int iRet = 2;//用户登录状态:0 成功登陆;1 退出;2 注销;3 重启 

            frmLogin NewfrmLogin = new frmLogin();
            switch (NewfrmLogin.ShowDialog())
            {
                case DialogResult.Yes:
                    {
                        iRet = 0;//登录成功状态
                        NewfrmLogin.Close();
                        break;
                    }
                case DialogResult.Cancel:
                    {
                        iRet = 1;//登录取消,退出
                        break;
                    }
                case DialogResult.Retry:
                    {
                        iRet = 3;//中止登录,重启程序
                        Process myProcess = new Process();
                        myProcess.StartInfo.FileName = @"App.exe";
                        myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                        myProcess.Start();
                        break;
                    }
                default:
                    {
                        iRet = 1;//发生不可预计的情况,退出
                        break;
                    }
            }
            if (iRet == 0)
            {
                return true;
            }

            return false;
        }

        public bool ShowMidForm(LoginManager loginManager, Form frmCurr)
        {
            if (frmCurr != null)
            {
                loginManager.IsExit = false; //置为false,以防结束main(),退出系统,参见FrmMDI_FormClosed的判断
                frmCurr.Close();
                frmCurr.Dispose();
            }

            //frmCurr = new FrmMDI(loginManager);
            frmCurr = new MetroMDI(loginManager);
            frmCurr.Show();
            return true;
        }


        public bool VerifyLicence()
        {
            bool flag = false;
            Comm.Licence licence = new Comm.Licence();
            WebConfig m_wc = new WebConfig();
            m_wc.WebConfigPath = Directory.GetParent(Application.ExecutablePath).ToString() + @"\app.exe.config";
            string licencePath = m_wc.GetWebConfig(WebConfig.MyCMMIConfiguration, "MyCMMI.MyCMMI.LicencePath");

            switch (licence.VerifyLicence(licencePath))
            {
                case LicenceStatus.NoStart:
                    MessageBox.Show("还未到许可证许可的启用时间!", "Contamination Explorer 信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case LicenceStatus.OverCount:
                    MessageBox.Show("用户数超过许可证的许可数!", "Contamination Explorer 信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case LicenceStatus.Overdue:
                    MessageBox.Show("许可证已过期!", "Contamination Explorer 信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case LicenceStatus.VerifyFail:
                    MessageBox.Show("验证许可证失败!", "Contamination Explorer 信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case LicenceStatus.VerifySucceed:
                    flag = true;
                    break;
            }
            return flag;
        }

        /// <summary>
        /// 检测App.exe.config文件并且获取WebService的Url
        /// </summary>
        public bool CheckAppConfigWebService()
        {
            FileInfo fi = new FileInfo(GlobalConfig.CLIENTCONFIGNAME);

            if (!fi.Exists)
                return false;

            GlobalConfig globalconfig = new GlobalConfig();

            if (String.IsNullOrEmpty(globalconfig.WebServiceUrl.Trim()))
            {
                //todo 多语言
                MessageBox.Show("客户端设置文件已损坏!\n请联系系统管理员!\n是否继续运行程序?", "软件测试 信息");
                return false;
            }
            
            return true;
        }

        //检测本地客户端的主版本并与升级服务器端的最新客户端进行比较
        public bool CheckNewVersion()
        {
            Cursor.Current = Cursors.WaitCursor;
            CheckVersion checkversion = new App.CheckVersion();
            if (checkversion.SkipCheck)
            {
                try
                {
                    checkversion.StartCheck();
                    switch (checkversion.CompareVersion())
                    {
                        case 0:
                            break;
                        case 1:
                            if (MessageBox.Show("已检测到存在更新的版本,您是否要现在进行更新?", "MyCMMI 客户端自动更新", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                            {
                                checkversion.CallUpdateFile();
                                return false;
                            }
                            break;
                        case 2:
                            if (MessageBox.Show("已检测到存在一个比当前更旧的版本,您是否要现在进行更新?", "MyCMMI 客户端自动更新", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                            {
                                checkversion.CallUpdateFile();
                                return false;
                            }
                            break;
                        default:
                            {
                                break;
                            }
                    }
                }
                catch (Exception e)
                {
                    if (MessageBox.Show("无法连接到升级服务器!请联系系统管理员!\n是否继续运行程序?", "自动更新失败", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.No)
                    {
                        return false;
                    }
                }
            }

            return true;
        }
        //检测当前用户所用的网络服务器是否在当前客户端支持的范围内
        public bool CheckCurrWebService()
        {
            Cursor.Current = Cursors.WaitCursor;

            GetServiceVersion f_GetServiceVerion = new GetServiceVersion();
            if (f_GetServiceVerion.CanCheckWebServiceVersion)
            {
                //f_GetServiceVerion.GetCurrentWebServiceVersion();
                if (string.IsNullOrEmpty(f_GetServiceVerion.CurrentWebServiceVersion))
                {
                    if (MessageBox.Show("无法连接到网络服务器,请联系系统管理员!\n是否继续运行程序?", "MyCMMI Client启动故障", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    {
                        return false;
                    }
                    //else
                    //{
                    //    f_GetServiceVerion.CanCheckWebServiceVersion = false;
                    //}
                }
            }
            if (!f_GetServiceVerion.CompareWebServiceVersion() && f_GetServiceVerion.CanCheckWebServiceVersion)
            {
                if (MessageBox.Show("已检测到您选用的网络服务器无法支持您当前的客户端版本!" + "\n" + "请联系系统管理员!\n是否继续运行程序?", "MyCMMI Client启动提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return false;
                }
            }

            return true;
        }
    }
}