Wednesday, April 7, 2010

An example code to simulate mouse programmatically in vb6



' Simulate moving the mouse to the center of the
' PictureBox and clicking.
Private Sub cmdClick_Click()
Const NUM_MOVES = 3000
Dim pt As POINTAPI
Dim cur_x As Single
Dim cur_y As Single
Dim dest_x As Single
Dim dest_y As Single
Dim dx As Single
Dim dy As Single
Dim i As Integer

    ' Things are easier working in pixels.
    ScaleMode = vbPixels
    picClicker.ScaleMode = vbPixels

    ' mouse_event moves in a coordinate system where
    ' (0, 0) is in the upper left corner and
    ' (65535,65535) is in the lower right corner.

    ' Get the current mouse coordinates and convert
    ' them into this new system.
    GetCursorPos pt
    cur_x = pt.X * 65535 / ScaleX(Screen.Width, vbTwips, _
        vbPixels)
    cur_y = pt.Y * 65535 / ScaleY(Screen.Height, vbTwips, _
        vbPixels)

    ' Convert the coordinates of the center of the
    ' picClicker PictureBox into this new system.
    pt.X = picClicker.ScaleWidth / 2
    pt.Y = picClicker.ScaleHeight / 2
    ClientToScreen picClicker.hwnd, pt
    dest_x = pt.X * 65535 / ScaleX(Screen.Width, vbTwips, _
        vbPixels)
    dest_y = pt.Y * 65535 / ScaleY(Screen.Height, vbTwips, _
        vbPixels)

    ' Move the mouse.
    dx = (dest_x - cur_x) / NUM_MOVES
    dy = (dest_y - cur_y) / NUM_MOVES
    For i = 1 To NUM_MOVES - 1
        cur_x = cur_x + dx
        cur_y = cur_y + dy
        mouse_event _
            MOUSEEVENTF_ABSOLUTE + _
            MOUSEEVENTF_MOVE, _
            cur_x, cur_y, 0, 0
        DoEvents
    Next i

    ' Move the mouse to its final destination and click it.
    mouse_event _
        MOUSEEVENTF_ABSOLUTE + _
        MOUSEEVENTF_MOVE + _
        MOUSEEVENTF_LEFTDOWN + _
        MOUSEEVENTF_LEFTUP, _
        dest_x, dest_y, 0, 0
End Sub