How to get the Browser UserAgent String in Visual Basic 6?

时间:2016-11-12 05:28:33

标签: visual-studio winapi vb6

I am trying to get the UserAgent of the default browser using the ObtainUserAgentString API in Visual Basic 6. I found the documentation on the MSDN and tried to convert it to Visual Basic 6 but it did not work.

C++ (MSDN)

HRESULT ObtainUserAgentString(
  _In_  DWORD  dwOption = 0,
  _Out_ LPCSTR *pcszUAOut,
  _Out_ DWORD  *cbSize
);

Visual Basic 6 API

Private Declare Function ObtainUserAgentString Lib "Urlmon.dll" (ByVal dwOption As Long, ByRef pcszUAOut As String, ByRef cbSize As Long) As Long

Private Function BrowserUserAgent() As String
Dim httpUseragent As String
Dim szhttpUserAgent As Long
httpUseragent = Space(512)
szhttpUserAgent = Len(httpUseragent)
Call ObtainUserAgentString(0, httpUseragent, szhttpUserAgent)
BrowserUserAgent = httpUseragent
End Function

Private Sub Command1_Click()
MsgBox BrowserUserAgent
End Sub

2 个答案:

答案 0 :(得分:3)

除了这是一个肮脏的旧ANSI入口点之外,您需要的所有内容似乎都有记录。

Option Explicit

Private Const NOERROR As Long = 0
Private Const E_OUTOFMEMORY As Long = &H8007000E

Private Enum UAS_OPTIONSENUM
    [_UAS_EXACTLEGACY] = &H1000&
    UAS_DEFAULT = 0
    UAS_7 = 7 'Compatible mode.
    UAS_7_LEGACY = 7 Or [_UAS_EXACTLEGACY]
    UAS_8 = 8
    UAS_9 = 9
    UAS_10 = 10
    UAS_11 = 11
End Enum

Private Declare Function ObtainUserAgentString Lib "urlmon" ( _
    ByVal dwOption As Long, _
    ByVal pcszUAOut As Long, _
    ByRef cbSize As Long) As Long

Private Function BrowserUserAgent( _
    Optional ByVal Options As UAS_OPTIONSENUM = UAS_DEFAULT) As String
    Const MAX_BUFFER As Long = 2048
    Dim Size As Long
    Dim Buffer() As Byte
    Dim HRESULT As Long

    Do
        Size = Size + 128
        ReDim Buffer(Size - 1)
        HRESULT = ObtainUserAgentString(Options, VarPtr(Buffer(0)), Size)
    Loop While HRESULT = E_OUTOFMEMORY And Size < MAX_BUFFER
    If HRESULT = NOERROR Then
        BrowserUserAgent = StrConv(LeftB$(Buffer, Size - 1), vbUnicode)
    Else
        Err.Raise &H8004D000, _
                  , _
                  "ObtainUserAgentString error &H" & Hex$(HRESULT)
    End If
End Function

Private Sub Form_Load()
    AutoRedraw = True
    Print BrowserUserAgent()
    Print BrowserUserAgent(UAS_7)
    Print BrowserUserAgent(UAS_7_LEGACY)
    Print BrowserUserAgent(UAS_8)
    Print BrowserUserAgent(UAS_11)
End Sub

Screenshot

答案 1 :(得分:2)

HRESULT ObtainUserAgentString(
  _In_  DWORD  dwOption = 0,
  _Out_ LPCSTR *pcszUAOut,
  _Out_ DWORD  *cbSize
);

Param 2是LongPointerCString。你总是传递C字符串ByVal,它实际上传递了B String ByRef的C字符串部分。如果它是一个IN参数,你将不得不用一个真正的C字符串所具有的Chr(0)来结束该字符串。

  

字符串参数是一种特殊情况。按值传递字符串意味着您传递字符串中第一个数据字节的地址;通过引用传递字符串意味着您正在传递存储另一个地址的存储器地址;第二个地址实际上是指字符串的第一个数据字节。如何确定使用哪种方法将在本章后面的“将字符串传递给DLL过程”主题中进行说明。

从帮助中的Visual Basic概念。