2014-03-27 23 views
1

VB.net应用程序启动当我尝试设置/打开注册表键我有例外:在启动

Requested registry access is not allowed. 

我可以设置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 
+2

您正在对用户的机器进行**重大**更改。这*要求*通过UAC提示告诉用户。隐藏它对用户希望保持其机器稳定性是一大损害。它不能工作,这是强制执行的。 –

回答

5

启动应用程序,未升高,然后上升,如果你需要。记住

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 

熊,虽然用户可能不能够(或希望)提升到管理员级别:

可以使用的方法类似这样的重启提升应用程序。