用FindWindowEx
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
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
Private 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
Private Const WM_KEYDOWN = &H100
Private Const WM_KEYUP = &H101
Dim x
Private Sub Command1_Click()
AppActivate x
Dim NotepadHwnd As Long, hwnd As Long
NotepadHwnd = FindWindow("notepad", vbNullString)
hwnd = FindWindowEx(NotepadHwnd, 0, "Edit", vbNullString) '得到窗口类名为Edit的窗口句柄
a = PostMessage(hwnd, WM_KEYDOWN, &HBB, 0&)
' a = PostMessage(hwnd, WM_KEYUP, &HBB, 0&)
End Sub
Private Sub Form_Load()
x = Shell("notepad.exe", vbNormalFocus)
End Sub
用这个 API 声明:
Private Declare Function GetDlgItem Lib "user32" Alias "GetDlgItem" (ByVal hDlg As Long, ByVal nIDDlgItem As Long) As Long
然后,
Dim hWnd As Long
hWnd = GetDlgItem ( hDlg , nIDDlgItem )
hDlg是窗口的句柄,nIDDlgItem是hDlg窗口内的控件的ID号,返回值hWnd就是控件的句柄。
Private Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, ByVal yPoint As Long) As Long
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Type POINTAPI
x As Long
y As Long
End Type
Dim n As POINTAPI
Dim a As Long
Private Sub Form_Load()
Timer1.Interval = 100
Label1.Caption = "移动鼠标指针"
End Sub
Private Sub Timer1_Timer()
GetCursorPos n
a = WindowFromPoint(n.x, n.y)
If a <> 0 Then
Dim s As String
s = String(100, Chr(0))
GetWindowText a, s, 100
Label1.Caption = "目标标题或文本: " & Trim(s)
Label2.Caption = "目标句柄为 " & a
End If
End Sub