Finding the X and Y co-ordinates of the
In many drawing applications, there is a small area that displays the current cursor
position on the screen. This is very simple to do and only requires one Windows API call.
The example below brings back the x and y co-ordinates of the current cursor position.
1. Start a new standard EXE project in Visual Basic; form1 is created by default.
2. Add a standard module to the project by clicking on project on the Visual Basic menu
and select 'Add Module'. Module1 is opened up by default.
3. Type the following, making sure that the API call is on one line
Type POINTAPI ' Declare types
x As Long
y As Long
Declare Function GetCursorPos Lib "user32" _
(lpPoint As POINTAPI) As Long ' Declare API
4. Open up Form1 and add two labels and one timer. Set the interval property of the
timer to 1. Open up the code window to form1 and type the following
Dim z As POINTAPI ' Declare variable
Private Sub Timer1_Timer()
GetCursorPos z ' Get Co-ordinets
Label1 = "x: " & z.x ' Get x co-ordinets
Label2 = "y: " & z.y ' Get y co-ordinets
5. Run the program, by pressing F5 or choose Start from the Run menu. Move the mouse
around and watch the two labels on Form1