Link to home
Start Free TrialLog in
Avatar of Gupi
Gupi

asked on

Controlling Mouse With KeyBoard

hi. Please tell me  in VB how do i move mouse pointer using keyboard ?
or how do i change the position of mouse pointer when i click or a command button or press enter when the focus is on it.
Very Urgent.
Quick Response is REQUESTED PLEASE.
Thanks.

Gupi
ASKER CERTIFIED SOLUTION
Avatar of Kani Str
Kani Str
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you want to move it relative to the current position then use the GetCursorPos() API to the current location and then you add/subtract to those values and then use SetCursorPos() as str_kani has suggested:
http://www.mentalis.org/apilist/GetCursorPos.shtml

Alternatively, you can use the mouse_event() API and specify relative coordinates.  You can also make mouse clicks using this API:
http://www.mentalis.org/apilist/mouse_event.shtml

Option Explicit

Private Const MOUSEEVENTF_LEFTDOWN = &H2
Private Const MOUSEEVENTF_LEFTUP = &H4
Private Const MOUSEEVENTF_MOVE = &H1
Private Const MOUSEEVENTF_ABSOLUTE = &H8000

Private 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)

Private Sub Form_Load()
    Me.KeyPreview = True
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    Select Case KeyCode
        Case vbKeyUp
            mouse_event MOUSEEVENTF_MOVE, 0, -1, 0, 0
           
        Case vbKeyRight
            mouse_event MOUSEEVENTF_MOVE, 1, 0, 0, 0
           
        Case vbKeyDown
            mouse_event MOUSEEVENTF_MOVE, 0, 1, 0, 0
           
        Case vbKeyLeft
            mouse_event MOUSEEVENTF_MOVE, -1, 0, 0, 0
           
        Case vbKeyReturn
            mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
            mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
           
    End Select
End Sub
Avatar of cjard
cjard

in control panel, in accessibility settings, turn on MOUSE KEYS..

microsoft already made keyboard control of the mouse.. dont reinvent the wheel!
(it's for handicapped people)
(or people like me who broke their mouse accidentally last week)