using System; using System.Security.Principal; using System.Windows.Forms; namespace TestProject { static class Program { /// /// 应用程序的主入口点。 /// [STAThread] static void Main() { try { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); //设置应用程序处理异常方式:ThreadException处理 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //处理UI线程异常 Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //启用异常记录日志的操作 //如果是管理员的身份 if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { Application.Run(new Form1()); } else { //创建启动对象 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); // 设置运行文件 startInfo.FileName = Application.ExecutablePath; //设置启动动作,确保以管理员身份运行 startInfo.Verb = "runas"; //如果不是管理员,则启动UAC System.Diagnostics.Process.Start(startInfo); //退出 System.Windows.Forms.Application.Exit(); } } catch (Exception) { throw; } } } }