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 Form, 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.

有帮助吗?

解决方案

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

VB.NET

Imports System.Windows.Forms

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

C#

using System.Windows.Forms;

public bool MouseIsOverControl(Control c)
{
    return c.ClientRectangle.Contains(c.PointToClient(Control.MousePosition));
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top