سؤال

When i try to set / open registry key i got exception:

Requested registry access is not allowed.

I can set requestedExecutionLevel key to requireAdministrator, but i don't want each time, when application starts see admin prompt. And some users does not have administrator rights. It would perfect to request administrator rights on demand.

Code With i already tried:

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
هل كانت مفيدة؟

المحلول

Start your application un-elevated and then elevate if you need to.

You can use a method like this to restart the application elevated:

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

Bear in mind though that the user may not be able to (or want to) elevate to administrator level.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top