确定鼠标是否在控件上? (在控制像素范围内)

时间:2014-01-13 17:52:41

标签: .net vb.net mouse bounds mouse-position

我正在尝试编写一个函数来确定鼠标是否超出像素范围(特定控件的像素范围)

问题是该函数仅适用于Form的边界,不适用于按钮或我测试过的任何其他控件......我缺少什么?

''' <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:我知道鼠标事件的用法,但此功能仅供一般使用。

1 个答案:

答案 0 :(得分:7)

您需要将MousePosition转换为客户端坐标并测试控件的ClientRectangle

<子> 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));
}