SendInput VB Basic Example

后端 未结 2 1438
耶瑟儿~
耶瑟儿~ 2021-01-14 04:03

I hope someone can assist, I trying to find an example of a SendInput code that simulate keyboard commands, I wish to find the notepad window and enter a test message.

2条回答
  •  再見小時候
    2021-01-14 04:14

    The following code is not for VB.net but VB/VBA, its similar to the sendkeys method but probably a little more reliable as it sends the keys specifically to the target application. (the post where i got it shows the sendkeys method too)

    Public Declare Function FindWindowX Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, _
    ByVal hWnd2 As Long, ByVal lpsz1 As Long, ByVal lpsz2 As Long) As Long
    
    Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName 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
    
    Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Integer, ByVal lParam As Integer) As Long
    
    Private Const WM_KEYDOWN = &H100
    Private Const WM_KEYUP = &H101
    
    Sub Three()
        hWind = FindWindow(vbNullString, "Untitled - Notepad")
        cWind = FindWindowX(hWind, 0, 0, 0)
        Debug.Print PostMessage(cWind, WM_KEYDOWN, vbKeyA, 0)
        Debug.Print PostMessage(cWind, WM_KEYDOWN, vbKeyB, 0)
        Debug.Print PostMessage(cWind, WM_KEYDOWN, vbKeyC, 0)
    End Sub
    

    Code taken from this forum post

    If you paste this into a new module in Excel/VBA and have an new instance of notepad running, when the sub is executed "abc" should appear in notepad.

    I don't see how using this, or the sendkeys method could "damage" the target window. So long as you time the messages properly (not sending tonnes of characters to the window all at the same time) it shouldn't cause any problems.

提交回复
热议问题