8

我需要一些代码,将管理员权限图标添加到命令按钮并在单击此类按钮时显示提示。我怎样才能在 VB6 中做到这一点?某些操作需要管理员权限,因为它们会替换 Windows Vista/7 不允许程序正常访问文件的文件和内容。

4

4 回答 4

8

这是一个 ShellExecuteEx 的 VB6 示例,它允许您有选择地执行具有管理员权限的任何进程。您可以将其放入模块或类中。

Option Explicit

Private Const SEE_MASK_DEFAULT = &H0

Public Enum EShellShowConstants
        essSW_HIDE = 0
        essSW_SHOWNORMAL = 1
        essSW_SHOWMINIMIZED = 2
        essSW_MAXIMIZE = 3
        essSW_SHOWMAXIMIZED = 3
        essSW_SHOWNOACTIVATE = 4
        essSW_SHOW = 5
        essSW_MINIMIZE = 6
        essSW_SHOWMINNOACTIVE = 7
        essSW_SHOWNA = 8
        essSW_RESTORE = 9
        essSW_SHOWDEFAULT = 10
End Enum

Private Type SHELLEXECUTEINFO
        cbSize        As Long
        fMask         As Long
        hwnd          As Long
        lpVerb        As String
        lpFile        As String
        lpParameters  As String
        lpDirectory   As String
        nShow         As Long
        hInstApp      As Long
        lpIDList      As Long     'Optional
        lpClass       As String   'Optional
        hkeyClass     As Long     'Optional
        dwHotKey      As Long     'Optional
        hIcon         As Long     'Optional
        hProcess      As Long     'Optional
End Type

Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long

Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
    Dim SEI As SHELLEXECUTEINFO

    On Error GoTo Err

    'Fill the SEI structure
    With SEI
        .cbSize = Len(SEI)                  ' Bytes of the structure
        .fMask = SEE_MASK_DEFAULT           ' Check MSDN for more info on Mask
        .lpFile = FilePath                  ' Program Path
        .nShow = ShellShowType              ' How the program will be displayed
        .lpDirectory = PathGetFolder(FilePath)
        .lpParameters = EXEParameters       ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
        .hwnd = hWndOwner                   ' Owner window handle

        ' Determine launch type (would recommend checking for Vista or greater here also)
        If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
            .lpVerb = "runas"
        Else
            .lpVerb = "Open"
        End If
    End With

     ExecuteProcess = ShellExecuteEx(SEI)   ' Execute the program, return success or failure

    Exit Function
Err:
    ' TODO: Log Error
    ExecuteProcess = False
End Function

Private Function PathGetFolder(psPath As String) As String
    On Error Resume Next
    Dim lPos As Long
    lPos = InStrRev(psPath, "\")
    PathGetFolder = Left$(psPath, lPos - 1)
End Function
于 2011-01-21T18:34:28.023 回答
5

代码示例确实可以运行,但这里有一个显示“我的第二个实例”方法的简单示例。

该程序有一个带有一些公共功能的启动静态模块,包括一个“提升的操作”处理程序,以及一个上面只有一个命令按钮的表单:

模块1.bas

Option Explicit

Private Const BCM_SETSHIELD As Long = &H160C&

Private Declare Sub InitCommonControls Lib "comctl32" ()

Private Declare Function IsUserAnAdmin Lib "shell32" () As Long

Private Declare Function SendMessage Lib "user32" _
    Alias "SendMessageA" ( _
    ByVal hWnd As Long, _
    ByVal wMsg As Long, _
    ByVal wParam As Long, _
    ByRef lParam As Any) As Long

Private Declare Function ShellExecute Lib "shell32" _
    Alias "ShellExecuteA" ( _
    ByVal hWnd As Long, _
    ByVal lpOperation As String, _
    ByVal lpFile As String, _
    ByVal lpParameters As String, _
    ByVal lpDirectory As String, _
    ByVal nShowCmd As VbAppWinStyle) As Long

Private mblnIsElevated As Boolean

Public Function IsElevated() As Boolean
    IsElevated = mblnIsElevated
End Function

Public Sub OperationRequiringElevation(ByRef Params As Variant)
    MsgBox "Insert logic here for: " & vbNewLine _
         & Join(Params, vbNewLine)
End Sub

Public Sub RequestOperation( _
    ByVal hWnd As Long, _
    ByVal Focus As VbAppWinStyle, _
    ByRef Params As Variant)

    ShellExecute hWnd, "runas", App.EXEName & ".exe", _
                 Join(Params, " "), CurDir$(), Focus
End Sub

Public Sub SetShield(ByVal hWnd As Long)
    SendMessage hWnd, BCM_SETSHIELD, 0&, 1&
End Sub

Private Sub Main()
    If Len(Command$()) > 0 Then
        'Assume we've been run elevated to execute an operation
        'specified as a set of space-delimited strings.
        OperationRequiringElevation Split(Command$(), " ")
    Else
        mblnIsElevated = IsUserAnAdmin()
        InitCommonControls
        Form1.Show
    End If
End Sub

Form1.frm

Option Explicit

Private Sub Command1_Click()
    Dim Params As Variant

    Params = Array("ReplaceFile", "abc", "123")
    If IsElevated() Then
        OperationRequiringElevation Params
    Else
        RequestOperation hWnd, vbHide, Params
    End If
End Sub

Private Sub Form_Load()
    If Not IsElevated() Then
        SetShield Command1.hWnd
    End If
End Sub

该应用程序有一个简单的“asInvoker”清单,选择了 Common Controls 6.0 程序集。

于 2011-01-25T21:17:50.997 回答
2

首先,获取当有人单击按钮时运行的代码,并将其放在单独的 exe 中。更改您的按钮单击代码以使用 ShellExecute 启动 exe。其次,为每个新的 exe 构建外部清单并让它指定 requireAdministrator。第三,向您的按钮发送 BCM_SETSHIELD 消息(您可能需要查找消息 ID 的数值)以使盾牌出现在它们上。

于 2011-01-21T01:02:26.153 回答
1


  1. 将所有需要提升的代码移到外部进程中。
  2. 向您的按钮发送BCM_SETSHIELD消息以添加盾牌图标。
  3. 将清单嵌入到这些进程中,告诉 Windows 它们需要提升。见下文。



为了强制 Vista 和更高版本在 UAC 中以管理员身份运行 VB6 exe,您必须将清单 xml 作为资源嵌入其中。步骤如下;

  1. 创建清单文件。将其命名为“YourProgram.exe.manifest”,它应包含以下内容。重要的一行是“requestedExecutionLevel”。更改属性以匹配您的 exe。

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>>
    <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
      <assemblyIdentity
        version="1.0.0.0"
        processorArchitecture="X86"
        name="YourProgram"
        type="win32"
      >
      <description>application description</description>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
        <security
          <requestedPrivileges>
            <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
          </requestedPrivileges>
        </security>
      </trustInfo>
    </assembly>
    
  2. 创建一个名为“YourProgram.exe.manifest.rc”的文件。它应该包含以下内容。

    #define CREATEPROCESS_MANIFEST_RESOURCE_ID 1
    #define RT_MANIFEST 24 CREATEPROCESS_MANIFEST_RESOURCE_ID
    RT_MANIFEST "YourProgram.exe.manifest"

  3. 使用 rc.exe 编译资源。它默认位于 C:\Program Files\Microsoft Visual Studio\COMMON\MSDev98\Bin。这将创建一个名为 YourProgram.exe.manifest.RES 的文件。语法是;

    rc /r YourProgram.exe.manifest.rc

  4. 将 .RES 文件添加到您的项目中。使用 VB6 中的资源编辑器加载项执行此操作。工具栏上的图标看起来像绿色块。如果您没有该图标,请确保它已在插件管理器中启用。如果不在插件管理器中,则需要在 C:\Program Files\Microsoft Visual Studio\VB98\Wizards\Resedit.dll 上 regsvr32。打开资源编辑器后,单击打开并选择您的 .RES 文件。

  5. 编译你的项目。

  6. 要仔细检查清单是否正确嵌入,您可以使用名为InspectExe的工具。在资源管理器中,转到 exe 的属性,如果清单已嵌入,您应该有一个清单选项卡(.Net 程序集也将具有此清单选项卡)。

  7. 尝试在 Vista 或更高版本上运行您的程序。如果确实启用了 UAC,它应该会立即出现提示。

于 2011-01-25T21:58:45.153 回答