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

て烟熏妆下的殇ゞ 提交于 2019-12-11 03:44:34

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/21098050/determine-whether-the-mouse-is-over-a-control-over-a-control-pixel-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!