'module
Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Boolean
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
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
Declare Function GetNextWindow Lib "user32" Alias "GetWindow" (ByVal hwnd As Long, ByVal wFlag As Long) As Long
Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Public Const WM_CHAR = &H102
Public hndl As Long
Public Function EnumWindowsProc(ByVal hwnd As Long, ByVal lParam As Long) As Boolean
Dim sSave As String, Ret As Long
Ret = GetWindowTextLength(hwnd)
sSave = Space(Ret)
GetWindowText hwnd, sSave, Ret + 1
If Trim(sSave) = "无标题 - 记事本" Then
hndl = hwnd
EnumWindowsProc = False
Else
EnumWindowsProc = True
End If
End Function
'form
Option Explicit
Sub sendCharToNotePad()
Dim hwnd As Long
Dim lpClassName As String
Dim nullpos As Long
EnumWindows AddressOf EnumWindowsProc, ByVal 0&
hwnd = GetNextWindow(hndl, 5)
Do While hwnd <> 0
lpClassName = Space(256)
Call GetClassName(hwnd, lpClassName, 256)
nullpos = InStr(lpClassName, Chr$(0))
If nullpos > 0 Then
lpClassName = Left$(lpClassName, nullpos - 1)
End If
If (Trim(lpClassName) = "Edit") Then '往记事本写内容
Exit Do
End If
hwnd = GetNextWindow(hwnd, 2)
Loop
Call PostMessage(hwnd, WM_CHAR, vbKey1, 0) '如果发送频繁,发送完sleep,另外postmessage没有sendmessage效果好,postmessage会放到消息发送队列,可能被冲掉的,如果要模拟按键,则改WM_CHAR参数
Call PostMessage(hwnd, WM_CHAR, vbKeyF1, 0)
Call PostMessage(hwnd, WM_CHAR, vbKeyTab, 0)
End Sub
Private Sub Command1_Click()
Call sendCharToNotePad
End Sub