时间:2021-07-01 10:21:17 帮助过:14人阅读
- <br>static void Main(string[] Args) <br>{ <br>/** <br>* 当前用户是管理员的时候,直接启动应用程序 <br>* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行 <br>*/ <br>//获得当前登录的Windows用户标示 <br>System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); <br>//创建Windows用户主题 <br>Application.EnableVisualStyles(); <br><br>System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); <br>//判断当前登录用户是否为管理员 <br>if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) <br>{ <br>//如果是管理员,则直接运行 <br><br>Application.EnableVisualStyles(); <br>Application.Run(new Form1()); <br>} <br>else <br>{ <br>//创建启动对象 <br>System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); <br>//设置运行文件 <br>startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; <br>//设置启动参数 <br>startInfo.Arguments = String.Join(" ", Args); <br>//设置启动动作,确保以管理员身份运行 <br>startInfo.Verb = "runas"; <br>//如果不是管理员,则启动UAC <br>System.Diagnostics.Process.Start(startInfo); <br>//退出 <br>System.Windows.Forms.Application.Exit(); <br>} <br>} <br> <br>打开程序集里的Program.cs文件,并将其中Main方法中的代码替换为以上代码即可实现程序默认以管理员身份运行。 <br><br>这篇博客本来早就应该发表的,可是由于网络等各种原因,一直到了现在才得以发表,网络问题很快就会得到解决,到时会继续恢复到每周一篇的更新频率,希望大家继续关注。