【问题标题】:VB.net Application launch at startupVB.net 应用程序在启动时启动
【发布时间】:2014-05-06 15:39:58
【问题描述】:

当我尝试设置/打开注册表项时出现异常:

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

【问题讨论】:

  • 您正在对用户的机器进行大量的更改。这需要通过 UAC 提示告诉用户它。隐藏它极大地损害了用户保持机器稳定的愿望。而且它不起作用,这是强制执行的。

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


【解决方案1】:

在未提升的情况下启动您的应用程序,然后在需要时提升。

您可以使用这样的方法重新启动提升的应用程序:

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

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

【讨论】:

    猜你喜欢
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    相关资源
    最近更新 更多