Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vbscript - VBS send mouse clicks?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...