|
本帖最后由 Manrce 于 2020-1-19 15:24 编辑
限于有限的办公环境,无法安装其他软件,一直想用自带的VBA多软件办公自动化。而要用vba操作不同的程序,首先要获取其句柄。本案例是在学习HOOK的知识中想到的,借鉴了一部分。
主要思路:
1、获取鼠标位置所在的窗口句柄
1.1、GetCursorPos获得鼠标位置
1.2、WindowFromPoint获取鼠标位置的句柄
2、通过按键反馈当前鼠标所在位置的句柄
2.1 SetWindowsHookEx通过hook拦截信息
2.2 WH_KEYBOARD_LL全局监控键盘操作
2.3 确定按键正确运行获取鼠标位置句柄
代码如下:
- Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
- Public Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal ncode As Long, ByVal wParam As Long, lParam As Any) As Long
- Public Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
- Public Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, ByVal hmod As Long, ByVal dwThreadId As Long) As Long
- Public Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, ByVal yPoint As Long) As Long
- Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
- Public Const WH_KEYBOARD_LL = 13
- Public Const WM_KEYDOWN = &H100
- Public hHook As Long '定义钩子
- Public nakey As EVENTMSG '定义键盘指令
- Public windowshwnd As Long '定义Gethwnd获取的句柄
- Public Type EVENTMSG '定义键盘返回类型
- vKey As Long
- sKey As Long
- flag As Long
- time As Long
- End Type
- Public Type POINTAPI '得到鼠标坐标类型GetCursorPos(POINTAPI)
- X As Long
- Y As Long
- End Type
- Public Function MyKBHook(ByVal ncode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
- Dim a As String
- If ncode = 0 Then
- If wParam = WM_KEYDOWN Then
- CopyMemory nakey, ByVal lParam, LenB(nakey)
- a = Chr(nakey.vKey)
- If a = "E" Then
- Call getwindowhwnd
- Gethwnd.TextBox1.Value = windowshwnd
- End If
- End If
- End If
- End Function
- Sub ADDHOOK()
- hHook = SetWindowsHookEx(WH_KEYBOARD_LL, AddressOf MyKBHook, Application.Hinstance, 0)
- End Sub
- Sub UNHOOK()
- UnhookWindowsHookEx hHook
- hHook = 0
- End Sub
- Public Function getwindowhwnd()
- Dim p As POINTAPI
- GetCursorPos p
- windowshwnd = WindowFromPoint(p.X, p.Y)
- End Function
复制代码
获得句柄.7z
(16.47 KB, 下载次数: 61)
|
|