Windows的键盘事件被分解成: KeyDown + KeyUp,按键按顺序分别发送
如: Ctrl + Delete按键事件,在Windows中响应为
下面的示例,显示了如何向指定窗口发送Ctrl + Del事件
- KeyDown + Control
- KeyDown + Delete
- KeyUp + Delete
- KeyUp + Control
Option Explicit Public Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hWnd As Long,ByVal wMsg As Long,ByVal wParam As Long,ByVal lParam As Long) As Long Public Const WM_KEYUP = &H101 Public Const WM_KEYDOWN = &H100 Public Const VK_CONTROL = &H11 Public Const VK_DELETE = &H2E Public Sub Main() Dim hWnd As Long hWnd = 1836342 '' 这是我的测试窗口 APISendKeys hWnd,Array(VK_CONTROL,VK_DELETE) End Sub '' 使用API将一个或多个按键消息发送到活动窗口(将按键事件分解成基本元素) Public Sub APISendKeys(ByVal hWnd As Long,ByRef aKeys As Variant) Dim i As Long Dim nUBound As Long nUBound = SafeUBound(aKeys) If nUBound < 0 Then Exit Sub For i = 0 To nUBound If Not IsNumeric(aKeys(i)) Then Exit Sub If aKeys(i) < 0 Then Exit Sub Next 'i '' 逐元素发送 For i = 0 To nUBound PostMessage hWnd,WM_KEYDOWN,aKeys(i),0 Next 'i For i = nUBound To 0 Step -1 PostMessage hWnd,WM_KEYUP,0 Next 'i End Sub '' 安全UBound Public Function SafeUBound(ByRef aArray As Variant) On Error GoTo label_error: SafeUBound = UBound(aArray) Exit Function label_error: SafeUBound = -1 End Function原文链接:https://www.f2er.com/vb/259528.html