rainstormmaster的blog
rainstormmaster的blog

其实没什么说的,只是最近一段时间问的人比较多,所以写上几句
简单的说,有两个需要注意的地方,一是要用postmessage发送消息,二是这两个消息lparam参数比较复杂,发送消息的时候要构造好lparam参数,下面给出示例代码:
Option Explicit
Private Declare Function MapVirtualKey Lib "user32" Alias "MapVirtualKeyA" (ByVal wCode As Long, ByVal wMapType As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
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 Const WM_KEYDOWN = &H100
Private Const WM_KEYUP = &H101
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 Sub Command1_Click()
    Dim jsb As Long
    jsb = FindWindow("notepad", vbNullString)
    Dim mhwnd As Long
    mhwnd = FindWindowEx(jsb, 0, "edit", vbNullString)
    Dim lParam As Long
    lParam = makelparam(vbKey5, False)
    PostMessage mhwnd, WM_KEYDOWN, vbKey5, lParam
    lParam = makelparam(vbKey5, True)
    PostMessage mhwnd, WM_KEYUP, vbKey5, lParam
End Sub

Private Function makelparam(ByVal VirtualKey As Long, ByVal flag As Boolean) As Long
    Dim s As String
    Dim Firstbyte As String 'lparam参数的24-31位
    If flag = False Then 'keydown
        Firstbyte = "00"
    Else
        Firstbyte = "C0" 'keyup
    End If
    Dim Scancode As Long
    '获得虚拟键扫描码
    Scancode = MapVirtualKey(VirtualKey, 0)
    Dim Secondbyte As String 'lparam参数的16-23位,即虚拟键扫描码
    Secondbyte = Right("00" & Hex(Scancode), 2)
    s = Firstbyte & Secondbyte & "0001" '0001为lparam参数的0-15位,即发送次数
    makelparam = Val("&H" & s)
End Function

posted on 2006-03-24 10:19  学剑学诗两不成  阅读(5804)  评论(1编辑  收藏  举报