How to detect when the mouse leaves the form?

前端 未结 4 758
南笙
南笙 2020-12-11 21:23

I have a form with a lot of controls on it. How can I detect when the mouse leaves the form? I\'ve tried wiring up a MouseLeave event for every single control and the form

4条回答
  •  抹茶落季
    2020-12-11 22:12

    From looking at aygunes.myopenid.com's answer I made this version in Vb.Net that recursive adding MouseLeaveHandlers to all controls on the form and then Use the nice Clientrectangle.Contains(pt) to check if mousecursor is on or out of form. Working like a charm. Cred goes to aygunes.myopenid.com.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AddMouseLeaveHandlers()
    End Sub
    Sub AddMouseLeaveHandlers()
        For Each c As Control In Me.Controls
            HookItUp(c)
        Next
        AddHandler Me.MouseLeave, AddressOf CheckMouseLeave
    End Sub
    Sub HookItUp(ByVal c As Control)        
        AddHandler c.MouseLeave, AddressOf CheckMouseLeave
        If c.HasChildren Then
            For Each f As Control In c.Controls
                HookItUp(f)
            Next
        End If
    End Sub
    Private Sub CheckMouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim pt As Point = PointToClient(Cursor.Position)
        If ClientRectangle.Contains(pt) = False Then
            MsgBox("Mouse left form")
        End If
    End Sub
    

提交回复
热议问题