Mouse Out Event

One event that is noticably lacking from VB controls is a MouseOut event. The code below lets you create one. Please note that you need to change the hWnd that is checked in the tmrMouse_Timer() event to the control you want to monitor hovering over.

Add a timer to the form, called tmrMouse. Set its interval to 100. Also, add a command button called cmdHover.

'// VB Web Code Example
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, ByVal yPoint As Long) As Long
Private Type POINTAPI
        X As Long
        Y As Long
End Type
Private bHovering As Boolean
Private Sub MouseOut()
    cmdHover.Caption = "Move Mouse Here"
    bHovering = False
End Sub

Private Sub cmdHover_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
    If bHovering = False Then
        '// this event occurs a lot.
        '// only change the caption when we need to
        bHovering = True
        cmdHover.Caption = "Hovering..."
    End If
End Sub

Private Sub tmrMouse_Timer()
    Dim lpPos As POINTAPI
    Dim lhWnd As Long
    '// get the current pos
    GetCursorPos lpPos
    '// see if the mouse is currently over our form
    lhWnd = WindowFromPoint(lpPos.X, lpPos.Y)
    '// if it isn't over the button, then call the MouseOut procedure
    If lhWnd <> cmdHover.hWnd And bHovering = True Then MouseOut
End Sub

You might also like...


James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter” - Eric Raymond