Search code examples
vb6mouse

How to set the mouse cursor to a specified location on a label?


so i have developed this game in visual basic 6.0,a maze game in which i want my mouse cursor to be set on the start label on the form with maze and once the form is activated and gets focus!

Dim label1 As New label=Start

Solution

  • I've done similar tasks in the past using the Windows API. In the following example, a Form contains a Label named 'Label1' that is positioned somewhere on the Form. When the Form is Activated, the cursor will be centered on 'Label1':

    Option Explicit
    
    Private Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
    Private Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    
    Private Type RECT
       Left As Long
       Top As Long
       Right As Long
       Bottom As Long
    End Type
    
    Private Sub Form_Activate()
        Dim wr As RECT
        Dim tb As Long
        Dim le As Long
        Dim x As Long
        Dim y As Long
        
        'calculate coordinates
        Call GetWindowRect(Me.hwnd, wr)                                    'window coordinates
        tb = (Me.Height - Me.ScaleHeight) - (Me.Width - Me.ScaleWidth) / 2 'title bar height
        le = (Me.Width - Me.ScaleWidth) * 0.5                              'left edge of client area
        
        'calculate center of label
        x = wr.Left + ScaleX(le + Label1.Left + Label1.Width * 0.5, Me.ScaleMode, vbPixels)
        y = wr.Top + ScaleY(tb + Label1.Top + Label1.Height * 0.5, Me.ScaleMode, vbPixels)
        SetCursorPos x, y
    End Sub