VB.net应用程序在启动时启动

时间:2014-03-27 14:58:56

标签: .net vb.net uac elevated-privileges

当我尝试设置/打开注册表项时,我得到了异常:

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

1 个答案:

答案 0 :(得分: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

请记住,用户可能无法(或想要)提升到管理员级别。