LuckyLuke82 LuckyLuke82 - 3 months ago 38
Vb.net Question

tooltip under mouse cursor - flickering

I have set tooltip under mouse cursor, but It's flashing all the time, even If cursor doesn't move. Any ideas on how to prevent tooltip flickering ?

Code:

Private Sub DataGridView1_MouseHover(sender As Object, e As EventArgs) Handles DataGridView1.MouseHover


Dim cur = DataGridView1.HitTest(e.X, e.Y)

If cur.RowIndex >= 0 AndAlso cur.ColumnIndex >= 0 Then

DataGridView1.Cursor = Cursors.Help

ToolTip1.Active = True
Dim cp = Cursor.Position
cp.Y += CInt(Cursor.Size.Height * 0.2)
cp.X += CInt(Cursor.Size.Width * 0.8)
ToolTip1.Show("Details...", Me, PointToClient(cp))

Else
DataGridView1.Cursor = Cursors.Default
ToolTip1.Active = False
End If

End Sub

Answer

After some testing it appears that once the ToolTip is shown, the DataGridView temporarily loses focus. When it regains the focus the MouseMove event gets called again which causes the ToolTip to close and reshow itself again, and so it continues infinitely, eating CPU and some RAM, until you move the mouse outside a cell.

The simplest way to fix this is to make it check wether the mouse has moved or not since the last time MouseMove was called, then only reshow the ToolTip if the mouse has moved.

I used the CellMouseMove and CellMouseLeave events instead to save you the additional checking if the mouse is over a cell:

Dim PreviousCursorPos As New Point(-1, -1)

Private Sub DataGridView1_CellMouseMove(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseMove
    If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 AndAlso _
        PreviousCursorPos <> Cursor.Position Then 'If the mouse is not in the same position as before, then execute the code.

        DataGridView1.Cursor = Cursors.Help
        ToolTip1.Active = True

        Dim cp = Cursor.Position
        cp.Y += CInt(Cursor.Size.Height * 0.2)
        cp.X += CInt(Cursor.Size.Width * 0.8)

        ToolTip1.Show("Details...", Me, Me.PointToClient(cp))

        PreviousCursorPos = Cursor.Position
    End If
End Sub

Private Sub DataGridView1_CellMouseLeave(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellMouseLeave
    DataGridView1.Cursor = Cursors.Default
    ToolTip1.Active = False
End Sub

The ToolTip will flicker a bit when moving the mouse, but once it's still there won't be a problem.

Comments