2014-03-27 22 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 

熊,雖然用戶可能不能夠(或希望)提升到管理員級別:

可以使用的方法類似這樣的重啓提升應用程序。