Mouse
Very first step to trap a mouse pointer on the screen is grab the control over mouse position, once we get control over mouse position we can trigger mouse events. Without talking too much lets sum this article by putting VBA code where we will trap Mouse event and its position. I have mentioned both version APIs below which supports 64bit and 32 bit platform.
APIs and Constants
Following APIs must be placed in a General declaration section in a VBA standard module:
'Crsor Position #If Win64 Then Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As LongPtr, ByVal y As LongPtr) As LongPtr #Else Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long #End If 'Mouse Event #If Win64 Then Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As LongPtr, ByVal dx As LongPtr, ByVal dy As LongPtr, ByVal cButtons As LongPtr, ByVal dwExtraInfo As LongPtr) #Else 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) #End If 'Constants Public Const MOUSEEVENTF_LEFTDOWN = &H2 Public Const MOUSEEVENTF_LEFTUP = &H4 Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8 Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
Set Mouse Position
Public Sub SetCursorPosition() 'Reset mouse event mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 'Set cursor position constants Dim oLeft As Long oLeft = 10 Dim oTop As Long oTop = 700 'Set cursor position to left bottom of the screen SetCursorPos oLeft, oTop 'Reset mouse event mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 End Sub
Output
This method will set cursor pointer position at bottom left corner on the screen
Single Click
Public Sub SingleMouseClick() 'Set cursor position constants Dim oLeft As Long oLeft = 70 Dim oTop As Long oTop = 395 'Set cursor position to left bottom of the screen SetCursorPos oLeft, oTop 'Execute click mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0 End Sub
Output
It will perform single click on the screen on given position
Double Click
Private Sub MouseDoubleClick() 'Set cursor position constants Dim oLeft As Long oLeft = 70 Dim oTop As Long oTop = 395 'Set cursor position to left bottom of the screen SetCursorPos oLeft, oTop 'Execute double click mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0 mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0 End Sub
Output
It will double click on the screen on given position
Right Click
Private Sub MouseRightClick() 'Set cursor position constants Dim oLeft As Long oLeft = 120 Dim oTop As Long oTop = 400 'Set cursor position to left bottom of the screen SetCursorPos oLeft, oTop 'Execute Cursor mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0 mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0 End Sub
Output

Please subscribe to our blogs to keep your self upto date.