一、程序核心
本程序的核心是通过API函数获得窗口句柄并获得浏览器访问的网址,在此基础上可以实现用Winsock控件进行远程的监视和管理。
1.先创建一个工程并在窗口Form1中,并声明下面的四个API函数和两个常量:
Option Explicit Private Declare Function FindWindow Lib ″user32″ Alias ″FindWindowA″ (ByVal lpCl assName As String, ByVal lpWindowName As String) As Long
′Findwindow函数的功能是找到当前运行的IE窗口的url地址的句柄
Private Declare Function SendMessage Lib ″user32″ Alias ″SendMessageA″ (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long
′SendMessage函数的功能是向操作系统发送一条消息
Private Declare Function FindWindowEx Lib ″user32″ Alias ″FindWindowExA″ (ByVal hWnd1 As Long,ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
′FindwindowEx函数的功能是找到子窗体的句柄
Private Declare Function SendMessageByString Lib ″user32″ Alias ″SendMessageA″ (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
Private Const WM_GETTEXT = &HD
Private Const WM_GETTEXTLENGTH = &HE
2.在窗体上添加Command控件,并命名为GetURLstring,单击此命令按钮,并为其添加下面的程序代码:
Private Sub GetURLstring_Click()
On Error GoTo CallErrorA
Dim sClassName As String ′设定一个字符串变量,是类变量
Dim lhwnd As Long ′设定一个长整形变量用来接收函数返回值
Dim WindowHandle As Long ′设定一个长整形变量用来接收函数的返回句柄
lhwnd = 0
sClassName = (″IEFrame″)
lhwnd = FindWindowEx(lhwnd, 0, sClassName, vbNullString) ′获得URL地址栏的句柄,获得IE窗口的句柄
sClassName = (″WorkerA″)
lhwnd = FindWindowEx(lhwnd, 0, sClassName, vbNullString) ′获得IE窗口的工作区的句柄
sClassName = (″ReBarWindow32″)
lhwnd = FindWindowEx(lhwnd, 0, sClassName, vbNullString) ′获得IE窗口的菜单栏的句柄
sClassName = (″ComboBoxEx32″)
lhwnd = FindWindowEx(lhwnd, 0, sClassName, vbNullString) ′获得IE窗口的下拉菜单的句柄
sClassName = (″ComboBox″)
lhwnd = FindWindowEx(lhwnd, 0, sClassName, vbNullString) ′获得IE窗口的下拉菜单当前项的句柄
sClassName = (″Edit″)
lhwnd = FindWindowEx(lhwnd, 0, sClassName, vbNullString) ′获得这个下拉菜单的编辑框句柄
WindowHandle = lhwnd ′接收当前我们想要的句柄
Dim buffer As String ′设定字符串变量接收当前的字符串
Dim TextLength As Long ′设定长整形变量接收字符串的长度
TextLength = SendMessage(WindowHandle, WM_GETTEXTLENGTH, 0&, 0&) ′向系统发送获得IE窗口的地址栏中的字符串长度命令
buffer = String(TextLength, 0) ′
Call SendMessageByString(WindowHandle, WM_GETTEXT, TextLength + 1, buffer) ′向系统发送获得IE窗体地址栏中的字符串命令
If buffer = ″″ Then
MsgBox ″MicroSoft InternetExplorer浏览器没有运行.″, vbOKOnly
Else
MsgBox buffer ′IE运行时显示当前网址
End If
Exit Sub
CallErrorA:
MsgBox Err.Description
Err.Clear
End Sub