Friday, June 10, 2011

VB.Net code to control mouse movement and click

VB.Net code to perform mouse movements and clicks.


Include references at the top of the class code file to Windows interface libraries:

Public Declare Auto Function SetCursorPos Lib "User32.dll" (ByVal X As Integer, ByVal Y As Integer) As Integer
Public Declare Auto Function GetCursorPos Lib "User32.dll" (ByRef lpPoint As Point) As Integer
Public Declare Sub mouse_event Lib "user32" Alias "mouse_event" (ByVal dwFlags As Integer, ByVal dx As Integer, ByVal dy As Integer, ByVal cButtons As Integer, ByVal dwExtraInfo As Integer)

Some fixed constant values will be needed, so include these as basic names:

Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Public Const MOUSEEVENTF_MIDDLEDOWN = &H20
Public Const MOUSEEVENTF_MIDDLEUP = &H40
Public Const MOUSEEVENTF_RIGHTDOWN = &H8
Public Const MOUSEEVENTF_RIGHTUP = &H10
Public Const MOUSEEVENTF_MOVE = &H1


This provides three types of capabilities to move the mouse pointer, determine the mouse pointer location and to perform click events.

Set the mouse position on the screen:
Dim X As Integer, Y As Integer
X = 428
Y = 256
SetCursorPos(X, Y)

Get the mouse position on the screen:
Dim lpPoint As Point
GetCursorPos(lpPoint)
X = lpPoint.X
Y = lpPoint.Y
System.Diagnostics.Debug.WriteLine(String.Format("X: {0}, Y: {1}", X, Y)) 'output the current position to the debug window

Lastly, perform click operations, notice that a complete click is a "down" followed by "up" action, otherwise you're holding down the click button:
Call mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
Call mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)

Share Links