VBS send mouse clicks?

后端 未结 5 2078
陌清茗
陌清茗 2020-12-18 12:58

I need send mouse clicks from VBS. Like SendKeys. I have searched whole google, it seems there is no such function for VBS. Can you give me some solution?

5条回答
  •  佛祖请我去吃肉
    2020-12-18 13:45

    Here is a routine to send a left or right click to a window (using relative references) in VBA for Excel. Similar to AppActivate, you just need the window title.

    The arguments when you call the SendClick routine are:

    • Window Title (String)
    • Buttons (1 = Left, 2 = Right, -1 = Move mouse only; no click)
    • x (Relative position to window Left)
    • y (Relative position to window Top)

    Enjoy!

    'Declare mouse events
    Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    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 Const MOUSEEVENTF_LEFTDOWN = &H2
    Public Const MOUSEEVENTF_LEFTUP = &H4
    Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
    Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
    'Declare sleep
    Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
    
    ' Window location
    Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    Public Declare Function GetWindowRect Lib "user32" (ByVal hWnd As Long, lpRect As RECT) As Long
    Type RECT
      Left As Long
      Top As Long
      Right As Long
      Bottom As Long
    End Type
    
    Public Function WindowHandle(ByVal sTitle As String) As Long
        WindowHandle = FindWindow(vbNullString, sTitle)
    End Function
    
    Public Sub SendClick(sWnd As String, b As Integer, x As Long, y As Long)
        Dim pWnd As Long, pRec As RECT
    
        pWnd = WindowHandle(sWnd)
        GetWindowRect pWnd, pRec
    
        SetCursorPos pRec.Left + x, pRec.Top + y
        Sleep 50
        If b = 2 Then
            mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0
            Sleep 50
            mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
        ElseIf b <> -1 Then
            mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
            Sleep 50
            mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
        End If
    End Sub
    

提交回复
热议问题