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.

1 comment:

Anonymous said...

this part is not working in my vb6... (error msg)

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

Public Sub Mouse_Click(Check_Button As vButtons = vNothing)