keybd_event 是模拟键盘动作的API过程,即只能向当前激活的窗口模拟键盘动作,如果要向非激活的窗口发送键盘信息的话只能使用其他的API函数,下面我的程序就模拟了运行一个计算器程序,模拟在计算器的EDIT框内产生字符,并模拟了5+7=12的全部按键过程
新建一个窗体,添加一个command和一个text框并粘贴以下代码
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetDlgItem Lib "user32" (ByVal hDlg As Long, ByVal nIDDlgItem As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Integer, ByVal lParam As Any) 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 Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Const WM_SETTEXT = &HC
Private Const WM_KEYUP = &H101
Private Const WM_KEYDOWN = &H100
Private Const SW_SHOWNORMAL = 1
Private Sub Command1_Click()
Static i As Integer
Dim hwn As Long
Dim twn As Long
If i = 0 Then '运行计算器
Text1.Text = "运行计算器"
hwn = FindWindow(vbNullString, "计算器") '查找窗体名称为'计算器'的句柄
If hwn = 0 Then
Shell "calc.exe"
Else
ShowWindow hwn, SW_SHOWNORMAL '激活窗口
SetForegroundWindow hwn
End If
End If
If i = 1 Then '向计算器文本框发送文本'5ZqweSC'
Text1.Text = "向计算器文本框发送文本'5ZqweSC'"
hwn = FindWindow(vbNullString, "计算器")
twn = GetDlgItem(hwn, 403)
SendMessage twn, WM_SETTEXT, 0, "5ZqweSC"
End If
If i = 2 Then '计算器模拟按键Esc
Text1.Text = "计算器模拟按键Esc"
hwn = FindWindow(vbNullString, "计算器")
PostMessage hwn, WM_KEYDOWN, vbKeyEscape, 0
End If
If i = 3 Then '计算器模拟按键5
Text1.Text = "计算器模拟按键5"
hwn = FindWindow(vbNullString, "计算器")
PostMessage hwn, WM_KEYDOWN, vbKey5, 0
End If
If i = 4 Then '计算器模拟按键+
Text1.Text = "计算器模拟按键+"
hwn = FindWindow(vbNullString, "计算器")
PostMessage hwn, WM_KEYDOWN, vbKeyAdd, 0
End If
If i = 5 Then '计算器模拟按键7
Text1.Text = "计算器模拟按键7"
hwn = FindWindow(vbNullString, "计算器")
PostMessage hwn, WM_KEYDOWN, vbKey7, 0
End If
If i = 6 Then '计算器模拟按键Enter
Text1.Text = "计算器模拟按键回车"
hwn = FindWindow(vbNullString, "计算器")
PostMessage hwn, WM_KEYDOWN, vbKeyReturn, 0
End If
i = i + 1
If i = 7 Then i = 0
End Sub
温馨提示:答案为网友推荐,仅供参考