Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Beginner
Oct 1, 1996



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Moving the Mouse Pointer

Can you tell me if its possible to move the mouse cursor to a specific screen location and then return control of it to the user. If it is possible, could you indicate how?

Here is a tip from the VB Tips and Tricks file that shows a similar example of moving the pointer onto a command button.

Placing The Cursor On The Button That Has Focus

It is possible to move the mouse cursor by using a Windows API call. The instructions below illustrate how to use this method. In the declarations section of the module, place the following API declaration:

Declare Sub SetCursorPos Lib "User" (ByVal X As Integer, ByVal Y As Integer)
To move the cursor to a Command button on the window, for example, use the following code:
 x% = (Form1.Left + Command2.Left + Command2.Width / 2 + 60) / Screen.TwipsPerPixelX
 y% = (Form1.Top + Command2.Top + Command2.Height / 2 + 360) / 
 SetCursorPos x%, y%
This routine will place the mouse cursor approximately on the center of the Command2 button.

The calculation of the x and y coordinates for the SetCursorPos routine could use some explanation.

SetCursorPos expects these to be the pixel locations. In a 640 by 480 (standard VGA) screen, the command SetCursorPos 320, 240 would place the cursor in the center of the screen. Visual Basic, however, normally uses "twips" instead of pixels. The ratio of twips to pixels can vary depending on the screen mode. Fortunately, Visual Basic includes the TwipsPerPixelX and wipsPerPixelY properties so that we can easily convert VB's twips to Windows pixels.

In our example we calculate the x coordinate by taking the left property of our form, adding the left property of Command2 and half of the width of the button to get the center of the button. The "60" that we added is to compensate for the form's border. The y coordinate is calculated in the same manner. The "360" is to compensate for the form's border and the form's title bar.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date