Showing posts with label Mouse. Show all posts
Showing posts with label Mouse. Show all posts

Tuesday, August 19, 2008

Visual Basic 6: How to Simulate a Mouse Click

Sometimes, despite everything else you've tried you just need to simulate a mouse click somewhere. Again, not that difficult but not intuitive either.


'Start Module Code

Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dX As Long, ByVal dY As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)

Public Enum vButtons
vRightClick = 2
vDoubleRight = 4
vLeftClick = 8
vDoubleLeft = 16
End Enum

Public Const LEFTDOWN = &H2, LEFTUP = &H4, MIDDLEDOWN = &H20, MIDDLEUP = &H40, RIGHTDOWN = &H8, RIGHTUP = &H10

Public Sub Mouse_Click(Check_Button As vButtons = vNothing)

Select Case Check_Button
Case vRightClick
mouse_event RIGHTDOWN, 0&, 0&, 0&, 0&
mouse_event RIGHTUP, 0&, 0&, 0&, 0&

Case vDoubleRight
mouse_event RIGHTDOWN, 0&, 0&, 0&, 0&
mouse_event RIGHTUP, 0&, 0&, 0&, 0&
DoEvents
mouse_event RIGHTDOWN, 0&, 0&, 0&, 0&
mouse_event RIGHTUP, 0&, 0&, 0&, 0&

Case vLeftClick
mouse_event LEFTDOWN, 0&, 0&, 0&, 0&
mouse_event LEFTUP, 0&, 0&, 0&, 0&

Case vDoubleLeft
mouse_event LEFTDOWN, 0&, 0&, 0&, 0&
mouse_event LEFTUP, 0&, 0&, 0&, 0&
DoEvents
mouse_event LEFTDOWN, 0&, 0&, 0&, 0&
mouse_event LEFTUP, 0&, 0&, 0&, 0&

End Select
End Sub

'End Module Code


Using the code is simple: just find a spot where you need to simulate a mouse click and call the Mouse_Click() sub with one of the built in options (Right Click, Double Right Click, Left Click, Double Left Click). I typically use this in conjunction with SetCursorPos to move the pointer to a specific location and then call whichever click action I need at the time.

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.