Send clicks to another application

By | 2018-01-13

This code demonstrates how to send mouse clicks to another application using the SendInput API, in user32.dll.

First, you’ll want to place the following code in a module. This is where you define some constants, and make reference to the API you are going to use.

Public Structure MOUSEINPUT
    Public dx As Integer
    Public dy As Integer
    Public mouseData As Integer
    Public dwFlags As Integer
    Public dwtime As Integer
    Public dwExtraInfo As Integer
End Structure

Public Structure INPUT_TYPE
    Public dwType As Integer
    Public xi As MOUSEINPUT
End Structure

Private Declare Function SendInput Lib "user32.dll" (ByVal nInputs As Integer, ByRef pInputs As INPUT_TYPE, ByVal cbSize As Integer) As Integer

Private Const INPUT_MOUSE = 0
Private Const INPUT_KEYBOARD = 1
Private Const INPUT_HARDWARE = 2

Const M_MOVE = &H1
Const M_LD = &H2
Const M_LU = &H4

And this is the subroutine that will make the magic happen:

Public Sub ClickTheMouse()

    Dim inputEvents(0) As INPUT_TYPE

    inputEvents(0).xi.dx = 0
    inputEvents(0).xi.dy = 0
    inputEvents(0).xi.mouseData = 0
    inputEvents(0).xi.dwFlags = M_MOVE + M_LD + M_LU
    inputEvents(0).xi.dwtime = 0
    inputEvents(0).xi.dwExtraInfo = 0
    inputEvents(0).dwType = INPUT_MOUSE

    SendInput(1, inputEvents(0), Len(inputEvents(0)))
    SetCursorPos(xyC)

End Sub

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.