static void Main() { //0 在host 项目中 检测此项目是否已经启动 如果已经启动 那么发送请求到此 否则启动这个进程。hook 是一个自启动Windows服务。提供基础的host的监视保护钩子 //1程序启动的时候 检测是否同名的进程已经启动,不允许多个进程存在 //2 获取完毕UAC后 启动另一个端口的 http 监听,对控制器中的Action进行监听 //3 类似owin host的引用 //检测授权完毕。 var startForm = new MainForm(); HideOnStartupApplicationContext context = new HideOnStartupApplicationContext(startForm); Application.Run(context);//隐藏窗体的方法 }
/// <summary> /// 程序加载启动的时候事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_Load(object sender, EventArgs e) { //1 检测当前启动进程的用户是否在管理员权限组 var isInAdminGroup = this.IsUserInAdminGroup(); if (!isInAdminGroup) { SmartClient.Common.Logger.Error("您所在的用户组没有管理员权限!请联系本机系统管理员授权!"); MessageBox.Show("您所在的用户组没有管理员权限!请联系本机系统管理员授权!", "用户权限检测", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(0);//终止程序进程 及其子进程 return; } //2-1 如果是在XP 环境 那么弹出提示框(必须弹出提示,Web打开本地的程序 必须让用户知道启动了exe程序) // 2-2 Get and display the process elevation information (IsProcessElevated) // and integrity level (GetProcessIntegrityLevel). The information is not // available on operating systems prior to Windows Vista. if (Environment.OSVersion.Version.Major >= 6) { // Running Windows Vista or later (major version >= 6). UAC的时候 会提示框 try { //判断是否需要UAC提升权限 // Elevate the process if it is not run as administrator. if (!IsRunAsAdmin()) { // Launch itself as administrator ProcessStartInfo proc = new ProcessStartInfo(); proc.UseShellExecute = true; proc.WorkingDirectory = Environment.CurrentDirectory; proc.FileName = Application.ExecutablePath; proc.Verb = "runas"; try { //win7弹层 PopUACWindowTopLayerAsync(); Process.Start(proc); } catch { } finally { // The user refused the elevation.用户拒绝授权UAC 那么程序退出 System.Environment.Exit(0); //终止程序进程 及其子进程 } return; //执行完毕上述代码后 必须return 否则会出现下面的检测多个实例的异常 } } catch (Exception ex) { SmartClient.Common.Logger.Error(ex); MessageBox.Show(ex.Message, "打开程序授权UAC失败!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { //XP ---弹出确认框 var cfmResult = MessageBox.Show("是否确定开启智能打印客户端工作台程序?", "用户启动控制!", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); if (cfmResult != DialogResult.OK) { System.Environment.Exit(0); return; } } var isRunning = HideOnStartupApplicationContext.IsCurrentAppProcessHasRunning(); if (isRunning) { SmartClient.Common.Logger.Error("程序已经正在运行中!不允许运行多个实例!"); //MessageBox.Show("程序已经正在运行中!不允许运行多个实例!", "程序状态检测", MessageBoxButtons.OK, MessageBoxIcon.Stop); System.Environment.Exit(0);//终止程序进程 及其子进程 return; } //MessageBox.Show("okokokoko"); //3 通过了检测授权 开启Owin环境 try { RunOwinServer(); } catch (Exception ex) { //非正常启动 http监听 那么退出 并记录日志 Logger.Error(ex); System.Environment.Exit(0);//终止程序进程 及其子进程 } }