Kar*_*lis 1 .net vb.net uac elevated-privileges
当我尝试设置/打开注册表项时,我得到了异常:
Requested registry access is not allowed.
Run Code Online (Sandbox Code Playgroud)
我可以设置requestedExecutionLevel密钥requireAdministrator,但我不希望每次,当应用程序启动时看到管理员提示.有些用户没有管理员权限.它非常适合按需请求管理员权限.
代码我已经尝试过:
Dim regStartUp As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True)
Dim value As String
value = regStartUp.GetValue("App")
If value <> Application.ExecutablePath.ToString() & " startup" Then
regStartUp.CreateSubKey("App")
regStartUp.SetValue("App", Application.ExecutablePath.ToString() & " startup")
End If
Dim CommandLineArguments As String() = Environment.GetCommandLineArgs()
Dim i As Integer
Dim hideme As Boolean = False
For i = 0 To CommandLineArguments.GetUpperBound(0)
Console.WriteLine(CommandLineArguments(i) & vbCrLf)
If CommandLineArguments(i).ToLower() = "startup" Then
hideme = True
End If
Next
If hideme Then
Me.Hide()
End If
Run Code Online (Sandbox Code Playgroud)
如果需要,请提升您的应用程序,然后提升.
您可以使用这样的方法重新启动提升的应用程序:
Public Shared Sub RestartElevated(Optional ByVal args As String = "")
' Elevate the process if it is not run as administrator.
If (Not IsRunningAsAdmin()) Then
' Launch itself as administrator
Dim proc As New ProcessStartInfo
proc.UseShellExecute = True
proc.WorkingDirectory = Environment.CurrentDirectory
proc.FileName = Application.ExecutablePath
proc.Verb = "runas"
proc.Arguments = args
Try
Process.Start(proc)
Catch
' The user refused the elevation.
Return
End Try
Application.Exit() ' Quit itself
Else
'The process is already running as administrator
End If
End Sub
Public Shared Function IsRunningAsAdmin() As Boolean
Dim principal As New WindowsPrincipal(WindowsIdentity.GetCurrent)
Return principal.IsInRole(WindowsBuiltInRole.Administrator)
End Function
Run Code Online (Sandbox Code Playgroud)
请记住,用户可能无法(或想要)提升到管理员级别.