Monday, August 18, 2008

Visual Basic 6: How to Move the Mouse

Moving the Mouse isn't exactly difficult, but it's not exactly straight forward either. To make it happen in VB6 you have to use a couple of API calls.

Place the following code in a standard module:

'Start Module Code

Public Declare Function GetCursorPos Lib "user32" (lpPoint As _ POINTAPI) As Long

Public Declare Function SetCursorPos Lib "user32" (ByVal X As Long, _ ByVal Y As Long) As Long

Public Type POINTAPI
X As Long
Y As Long
End Type

Public a As POINTAPI
Public b As Long
Public c As Long

'End Module Code

You can then use the following code to perform some useful tasks:

GetCursorPos a
'This code will take the current cursor coordinates and will assign it to a.x and a.y.

SetCursorPos X, Y
'Where X and Y are the coordinates you want the mouse to end up at.

How do I use this code? Typically I make a button with a delay of a few seconds (using the Sleep API) followed by the GetCursorPos a code above. I then output the values of a.x and a.y to either a text field or a message box. This lets me map out the coordinates of where I want to put the cursor.

Once I know where I want the cursor to be I use the SetCursorPos X, Y code to move it.

No comments: