Search code examples
.netvb.netwinformsdatagridviewmouseevent

How to check if my mouse is inside the Datagridview?


I would like to check if my mouse is inside/outside the datagridview. If I had my mouse outside, it should run my timer code to begin a countdown before it hides the datagridview (2 seconds in my example).. and if it is inside, the timer should reset my counter to 0 so as to not hide my datagridview..

below is the code of my timer.. w/ 100 interval

Private ctme As Integer = 0
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If DataGridView1.Visible = False Then ctme = 0 : Exit Sub
        If Not DataGridView1.Bounds.Contains(PointToClient(Cursor.Position)) Then
            ctme = ctme + 1
            If ctme >= 20 Then
                ctme = 0
                DataGridView1.Visible = False
            End If
        Else
            ctme = 0
        End If
    End Sub

I have tried

Datagridview1.ClientRectangle.Contains(PointtoClient(Cursor.Position))

in place of

Datagridview1.Bounds.Contains(PointtoClient(Cursor.Position))

but still it doesnt work..

hope you could help me with this one..


Solution

  • You can use the MouseEnter (Occurs when the mouse pointer enters the control) and MouseLeave (Occurs when the mouse pointer leaves the control) events:

    using this the solution is much simpler:

    Private Sub DataGridView1_MouseEnter(sender As Object, e As EventArgs) Handles DataGridView1.MouseEnter
        Timer1.Stop()
    End Sub
    
    Private Sub DataGridView1_MouseLeave(sender As Object, e As EventArgs) Handles DataGridView1.MouseLeave
        Timer1.Start()
    End Sub
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Timer1.Interval = 2000
    End Sub
    
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        DataGridView1.Visible = False
    End Sub