Vb.Net修改WebBrowser控件UserAgent的方法
Imports System.Runtime.InteropServices
Imports System.Reflection
Public Class Form1
Dim isUserAgentSet As Boolean = False
<DllImport("urlmon.dll", CharSet:=CharSet.Ansi)> _
Private Shared Function UrlMkSetSessionOption(ByVal dwOption As Integer, ByVal pBuffer As String, ByVal dwBufferLength As Integer, ByVal dwReserved As Integer) As Integer
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Shared defaultUserAgent As String = Nothing
Const URLMON_OPTION_USERAGENT As Integer = &H10000001
''' <summary>
''' 在默认的UserAgent后面加一部分
''' </summary>
Public Shared Sub AppendUserAgent(ByVal Str As String)
If String.IsNullOrEmpty(defaultUserAgent) Then
defaultUserAgent = GetDefaultUserAgent()
End If
Dim ua As String = defaultUserAgent & Str
ChangeUserAgent(ua)
End Sub
''' <summary>
''' 修改UserAgent
''' </summary>
Public Shared Sub ChangeUserAgent(ByVal userAgent As String)
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, userAgent, userAgent.Length, 0)
End Sub
''' <summary>
''' 一个很BT的获取IE默认UserAgent的方法
''' </summary>
Private Shared Function GetDefaultUserAgent() As String
Dim wb As New WebBrowser()
wb.Navigate("about:blank")
While wb.IsBusy
Application.DoEvents()
End While
Dim window As Object = wb.Document.Window.DomWindow
Dim wt As Type = window.[GetType]()
Dim navigator As Object = wt.InvokeMember("navigator", BindingFlags.GetProperty, Nothing, window, New Object() {})
Dim nt As Type = navigator.[GetType]()
Dim userAgent As Object = nt.InvokeMember("userAgent", BindingFlags.GetProperty, Nothing, navigator, New Object() {})
Return userAgent.ToString()
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
AppendUserAgent("Tiancao.net")
' ChangeUserAgent("Tiancao.net")
MsgBox(GetDefaultUserAgent)
WebBrowser1.Refresh()
End Sub
End Class
without Security Concern Message
深度XP系统优化工具v1.66绿色版
欢迎关注微信公众账号ByCAD