How to Retrieve Mouse Cursor Coordinates in Visual Basic
This article was previously published under Q114777
This article has been archived. It is offered "as is" and will no longer be updated.
Applications such as Paint programs use functions from the Windows API(Application Programming Interface) to retrieve Mouse coordinates thatin turn help the user design and paint their picture. This article showsby example how to use the Windows API GetCursorPos() function to retrievethe mouse coordinates from Visual Basic.
The GetCursorPos() function returns a structure that contains the currentposition of the caret. To call the GetCursorPos() function from VisualBasic, you have to set up a Type structure. This is shown in thefollowing example.
- Start a new project in Visual Basic. Form1 is created by default.
- From the File Menu, choose New Module.
- Add the following code in the General Declarations section of the new module:
Type POINTAPI ' This holds the logical cursor information x As Integer y As Integer End Type Declare Sub GetCursorPos Lib "User" (lpPoint As POINTAPI)
- Add a timer control (Timer1) to the form.
- Add the following code to the Form_load event:
Sub Form_Load () timer1.Interval = 100 End Sub
- Add the following code to the Timer1_Timer event:
Sub Timer1_Timer () Dim rect As POINTAPI ' Get the current mouse cursor coordinates: Call GetCursorPos(rect) FORM1.Cls ' Print out current position on the form: Print "Current X = " & rect.x Print "Current Y = " & rect.y End Sub
- Run the Program. You should be able to see the cursor coordinates change whenever you move the mouse around the screen.
"Programming Windows: the Microsoft Guide to Writing Applications forWindows 3," Charles Petzold, Microsoft Press, 1990
"Microsoft Windows Software Development Kit" Reference Manuals andon-line help
WINSDK.HLP file shipped with Microsoft Windows 3.0 SoftwareDevelopment Kit
"Visual Basic Programmers Guide to the Windows API", Daniel Appleman,Ziff Davis Press, 1993
Article ID: 114777 - Last Review: 12/04/2015 10:11:13 - Revision: 2.0
Microsoft Visual Basic 3.0 Professional Edition, Microsoft Visual Basic 3.0 Professional Edition
- kbnosurvey kbarchive KB114777