マウスの操作

マウスの座標取得

'マウスの座標取得
Private Declare PtrSafe Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Type POINTAPI
    x As Long
    y As Long
End Type

'マウスの座標を出力
Public Sub printMousePosition()
    Dim Pos As POINTAPI
    GetCursorPos Pos
    Debug.Print "x(横軸): " & Pos.x
    Debug.Print "y(縦軸): " & Pos.y
End Sub

マウスの移動

Private Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long

Sub moveMouse()

    SetCursorPos 100, 100

End Sub

マウスのクリック

※一応動くけど仕組みはよくわからない

'マウスクリック操作
'https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mouse_event
Private Declare PtrSafe Sub mouse_event Lib "user32.dll" ( _
     ByVal dwFlags As Long, _
     ByVal dx As Long, _
     ByVal dy As Long, _
     ByVal cButtons As Long, _
     ByVal dwExtraInfo As Long)

Const MOUSEEVENTF_ABSOLUTE As Long = &H8000
Const MOUSEEVENTF_LEFTDOWN As Long = &H2
Const MOUSEEVENTF_LEFTUP As Long = &H4
Const MOUSEEVENTF_MIDDLEDOWN As Long = &H20
Const MOUSEEVENTF_MIDDLEUP As Long = &H40
Const MOUSEEVENTF_MOVE As Long = &H1
Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
Const MOUSEEVENTF_RIGHTUP As Long = &H10
Const MOUSEEVENTF_XDOWN As Long = &H80
Const MOUSEEVENTF_XUP As Long = &H100
Const MOUSEEVENTF_WHEEL As Long = &H800

Public Sub mouseLeftClick(ByVal x As Long, ByVal y As Long)
    SetCursorPos x, y
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub

'指定した座標で左クリックする
Sub testing()
    mouseLeftClick 300, 300
End Sub

便利関数Windows API

Posted by rafavba