;===============================================================================
; 说明: 向指定窗口发送虚拟按键消息
; 语法: _WinSendKey($sTitle, $sText, $cKey)
; 参数: $sTitle - 窗口标题或句柄
; $sText - 窗口包含文字
; $cKey - 按键
; 需要: 无
; 返回: 成功 - 1
; 失败 - 0, 并设置 @error 到
; 1 - 窗口不存在
; 2 - $cKey 无效
; 3 - API 操作失败, 设置 @extended 到返回值
; 备注: 按键暂时只支持 A-Z, 0-9, F1-F12, ENTER, ESCAPE, TAB 及光标键, 并且不支持组合键。格式同Send()
;===============================================================================
Func _WinSendKey($sTitle, $sText, $cKey)
Local $hWnd, $iKey, $aResult, $aError
Local Const $WM_KEYDOWN = 0x0100
Local Const $WM_KEYUP = 0x0101
If IsHWnd($sTitle) Then
$hWnd = $sTitle
Else
$hWnd = WinGetHandle($sTitle, $sText)
EndIf
If $hWnd = "" OR NOT WinExists($hWnd) Then Return SetError(1, 0, 0)
$cKey = StringUpper($cKey)
Switch $cKey
Case "{F1}"
$iKey = 0x0070
Case "{F2}"
$iKey = 0x0071
Case "{F3}"
$iKey = 0x0072
Case "{F4}"
$iKey = 0x0073
Case "{F5}"
$iKey = 0x0074
Case "{F6}"
$iKey = 0x0075
Case "{F7}"
$iKey = 0x0076
Case "{F8}"
$iKey = 0x0077
Case "{F9}"
$iKey = 0x0078
Case "{F10}"
$iKey = 0x0079
Case "{F11}"
$iKey = 0x007A
Case "{F12}"
$iKey = 0x007B
Case "{ENTER}"
$iKey = 0x000D
Case "{ESC}", "{ESCAPE}"
$iKey = 0x001B
Case "{TAB}"
$iKey = 0x0009
Case "{UP}"
$iKey = 0x0026
Case "{DOWN}"
$iKey = 0x0028
Case "{LEFT}"
$iKey = 0x0025
Case "{RIGHT}"
$iKey = 0x0027
Case Else
$iKey = Asc($cKey)
Switch $iKey
Case 48 To 57, 65 To 90
Case Else
Return SetError(2, 0, 0)
EndSwitch
EndSwitch
$aResult = DllCall("user32.dll", "int", "PostMessage", "hwnd", $hWnd, "uint", $WM_KEYDOWN, "wparam", $iKey, "lparam", 0)
$aError = DllCall("kernel32.dll", "int", "GetLastError")
If $aResult[0] <> 0 AND WinExists($hWnd) Then _
DllCall("user32.dll", "int", "PostMessage", "hwnd", $hWnd, "uint", $WM_KEYUP, "wparam", $iKey, "lparam", 0)
If $aResult[0] <> 0 Then
Return 1
Else
Return SetError(3, $aError[0], 0)
EndIf
EndFunc ;==>_WinSendKey