Centering The Mouse Pointer Over A Control

Positioning the cursor over the button they will are likely to make the action quicker and easier.

The following code will center the mouse cursor over any control that has an hWnd property.

Declare

#If Win32 Then
     Type RECT
           left As Long
           top As Long
           right As Long
           bottom As Long
     End Type
     Declare Sub GetWindowRect Lib "User32" (ByVal hWnd As _
           Long, lpRect As RECT)
     Declare Sub SetCursorPos Lib "User32" (ByVal X As _
           Long, ByVal Y As Long)
#Else
     Type RECT
           left As Integer
           top As Integer
           right As Integer
           bottom As Integer
     End Type
 
     Declare Sub GetWindowRect Lib "User" (ByVal hWnd _
           As Integer, lpRect As RECT)
     Declare Sub SetCursorPos Lib "User" (ByVal X As _
           Integer, ByVal Y As Integer)
#End If
Code
Sub CenterCursor(hWnd As Long)
Dim rPosition As RECT
#If Win32 Then
     Dim X As Long
     Dim Y As Long
#Else
     Dim X As Integer
     Dim Y As Integer
#End If
 
     GetWindowRect hWnd, rPosition
     X = (rPosition.right + rPosition.left) / 2
     Y = (rPosition.bottom + rPosition.top) / 2
     SetCursorPos X, Y
End Sub

Usage

CenterCursor hWnd:=Command1.hWnd

 

This tip is reprinted from the VB Tips & Tricks Volume 1 book.
Parts of this tip were submitted by: Donovan Olivier
Compatible With Visual Basic 4.0
Applies To Controls

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s