[英]WPF application - ask for administrator rights in runtime
Only a few options in my WPF application, need administrator rights.我的 WPF 应用程序中只有几个选项需要管理员权限。 I'd like to avoid compulsion to run the program as an administrator, so is there any opportunity to ask for administrator privileges in runtime, only in case of operation which requires this privileges?
我想避免强制以管理员身份运行程序,那么有没有机会在运行时要求管理员权限,仅在需要此权限的操作的情况下?
I don't think you can elevate an existing process.我认为您无法提升现有流程。 But I found a way in powershell 5 to start my script in a new elevated process.
但是我在 powershell 5 中找到了一种在新的提升进程中启动我的脚本的方法。 Hope this helps
希望这可以帮助
# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);
# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;
# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running as an administrator, so change the title and background colour to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
$Host.UI.RawUI.BackgroundColor = "DarkBlue";
Clear-Host;
}
else
{
# We are not running as an administrator, so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
$newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
Exit;
}
You can add to your project Application Manifest File (app.manifest)您可以添加到您的项目应用程序清单文件 (app.manifest)
and set requestedExecutionLevel to highestAvailable "/>并将requestedExecutionLevel设置为highestAvailable "/>
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC Manifest Options
If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following. -->
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
<!-- requestedExecutionLevel level="asInvoker" uiAccess="false" /-->
<!-- requestedExecutionLevel level="requireAdministrator" uiAccess="false" /-->
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.