65.9K
CodeProject 正在变化。 阅读更多。
Home

在启动时提升你的应用程序

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (3投票s)

2013年2月19日

CPOL

1分钟阅读

viewsIcon

13778

有时你需要以提升的权限运行你的应用程序才能解决 UAC 相关的问题。 

有时你需要以提升的权限运行你的应用程序才能解决 UAC 相关的问题。 如果你需要确保你的应用程序始终以管理员权限运行,这段代码可以帮助你。

Sub Main()
  Dim sArgs As String() = System.Environment.GetCommandLineArgs()

  If sArgs.Contains("-runasadmin") Then
    ' Running with elevated privileges
    SomeMethod()
  Else
    ' Re-launch the current application with elevated privileges
    ReDim Preserve sArgs(sArgs.Length + 1)
    sArgs(sArgs.Length - 1) = "-runasadmin"

    Dim oProcessStartInfo As System.Diagnostics.ProcessStartInfo = _
                             New ProcessStartInfo( _
                                 Reflection.Assembly.GetEntryAssembly().Location, _
                                 Join(sArgs, " "))
    oProcessStartInfo.Verb = "runas"

    Dim oProcess As New System.Diagnostics.Process()
    With oProcess
      ' Enable the WaitForExit method
      .EnableRaisingEvents = True
      .StartInfo = oProcessStartInfo

      ' Start the process.
      .Start()

      ' Sleep until the process has completed.
      .WaitForExit()
    End With
  End If
End Sub

我们首先要做的是获取命令行参数。为什么?这是告诉正在运行的应用程序我们想要它做一些特殊事情的最简单方法。

接下来需要确定我们是否正在以提升的权限运行。如果是,那就去执行我们应该做的事情。我过去用来确定我们是否已提升权限的方法是添加一个命令行参数 -runasadmin。请注意,这不是 Windows 添加的,而是由我的代码手动添加的。

如果代码没有以提升的权限运行,那么让我们重新启动应用程序并请求管理员权限。这是通过首先将 -runasadmin 添加到现有的命令行参数来实现的。创建一个 System.Diagnostics.ProcessStartInfo 对象,它将告诉我们的应用程序请求管理员权限。将动词 runas 添加到 System.Diagnostics.ProcessStartInfo 就是实现魔术的关键。创建一个新的 System.Diagnostics.Process,添加 System.Diagnostics.ProcessStartInfo。启动进程。等待子进程完成。

© . All rights reserved.