ElektroStudios ElektroStudios - 2 years ago 145
Vb.net Question

Determine whether the mouse is over a control? (over a Control pixel range)

I'm trying to write a function that should determine whether the mouse is over a range in pixels (the pixel range of a specific Control)

The problem is that the function only works for the bounds of the

, don't work for buttons or any other control that I've tested ...what I'm missing?

''' <summary>
''' Determinates whether the mouse pointer is over a pixel range of the specified control.
''' </summary>
''' <param name="Control">The control.</param>
''' <returns>
''' <c>true</c> if mouse is inside the pixel range, <c>false</c> otherwise.
''' </returns>
Private Function MouseIsOverControl(ByVal [Control] As Control) As Boolean

Return [Control].Bounds.Contains(MousePosition)

End Function

PS: I know the usage of the Mouse events, but this function is for generic usage.

Answer Source

You need to transform the MousePosition into client coordinates and test the ClientRectangle of the control.


Imports System.Windows.Forms

Public Function MouseIsOverControl(ByVal c As Control) As Boolean
    Return c.ClientRectangle.Contains(c.PointToClient(Control.MousePosition))
End Function


using System.Windows.Forms;

public bool MouseIsOverControl(Control c)
    return c.ClientRectangle.Contains(c.PointToClient(Control.MousePosition));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download