当前位置:首页 » 程序代码 » 正文

用VB做一个输入法:发送字符到其它窗口 方法3

发送字符或发送字符串到其它程序的输入框中,还可以用PostMessage这个API函数来解决,这里提供以一个VB代码,供大家参考。
它可以发送英文字符,中文字符,在运行时,也不管当时是否已经调用中文输入法,都可以成功向别的窗体里有焦点的编辑框中发送字符。

在做发送字符代码之前,先把让窗体无焦点的代码输入好,具体见上一篇文章 www.wb86.com/post/39.html
输入好使窗口无焦点的代码后,在窗口画一个标签,标签的点击事件代码是:
Private Sub Label1_Click()
    Dim hd As Long
    Dim ttHD As Long
    Dim msg As String
    Dim i As Integer
    Dim bytemsg() As Byte

    Me.WindowState = 1
    msg = "我的网站是 www.wb86.com" '要发送的字符

    hd = GetForegroundWindow()  '获取一个前台窗口的句柄
    ttHD = GetWindowThreadProcessId(hd, 0)
    AttachThreadInput ttHD, App.ThreadID, True
    hd = GetFocus
    AttachThreadInput ttHD, App.ThreadID, False

    bytemsg = StrConv(msg, vbFromUnicode) '这句保证发送中文字符没有乱码

    For i = LBound(bytemsg) To UBound(bytemsg)
        PostMessage hd, WM_CHAR, bytemsg(i), 0
    Next i
    Me.WindowState = 0
End Sub

由于要靠PostMessage来发送字符消息,所以在窗体模块还要引用相关的API函数,相关代码如下:
Private Declare Function GetForegroundWindow Lib "user32" () As Long
Private Declare Function GetFocus Lib "user32" () As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function AttachThreadInput Lib "user32" (ByVal idAttach As Long, ByVal idAttachTo As Long, ByVal fAttach As Long) 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_CHAR = &H102

打赏 支付宝打赏 微信打赏

来源:济亨网

本文链接:https://wb98.com/post/41.html

VB代码  API  
    << 上一篇 下一篇 >>

    湘公网安备 43011102000514号 - 湘ICP备08100508号