WinForm实现管理员权限运行的三种方式

我们的软件运行时,如果涉及到文件或者数据库操作的时候,可能会提示权限不足。一种比较简单的办法,就是右击以管理员权限运行,但是每次这么操作,又会比较麻烦,有没有什么更好的办法呢?今天跟大家分享一下WinForm程序以管理器权限运行的几种方法。

采用Process.Start方法

思路很简单,就是在Program.cs入口处判断当前是不是管理员权限,如果是,则不做其他处理,如果不是,改成管理员权限。

修改Main方法如下所示:

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

//获得当前登录的Windows用户标示
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
//如果是管理员,则直接运行
Application.Run(new FrmMain());
}
else
{
//创建启动对象
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
try
{
Process.Start(startInfo);
}
catch
{
return;
}
//退出
Application.Exit();
}
}

直接修改exe属性

右击exe程序文件,在弹出的属性对话框中,兼容性选项中,勾选“以管理员身份运行此程序”即可。

添加应用程序清单文件

这种方法也是我常用的一种方式。

点击项目,右击添加,新建项,选择应用程序清单列表。

添加完成后,打开app.manifest文件,将:

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

修改为:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

 

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注