Placing The Cursor On The Button That Has Focus

Wouldn’t it be nice if you could also place the mouse cursor over that button? Unfortunately, Visual Basic does not have a built-in method to accomplish this. I have found that it is possible to move the mouse cursor by using a Windows API (Application Programmer’s Interface) call. The instructions below illustrate how to use this method.

Start a new project which includes one form. Place two buttons on the form. Add a new module to the project (File, New Module). In the General, Declarations section of the module, place the following code, all on one line:

Declare Sub SetCursorPos Lib "User" (ByVal X As Integer, ByVal Y As Integer)

In the Click event for Command1, place 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%

Press F5 to run the program. When you click on Command1 the mouse cursor will be placed 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.

 

Tip Submitted By: Robert Wilcox


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.