Moving the Mouse Pointer

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) / Screen.TwipsPerPixelY 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 wipsPerPixelYproperties 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.

See also  The Art of AI-Generated Meeting Minutes

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist