检测光标是否在控件的范围内

P.B*_*key 17 c# winforms

我有一个用户控件

public partial class UserControl1 : UserControl, IMessageFilter
{
    public UserControl1()
    {
        InitializeComponent();
        Application.AddMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m)
    {
        var mouseLocation = Cursor.Position;

        if (Bounds.Contains(PointToClient(mouseLocation)))
        {
            bool aBool = true;//breakpoint
            bool two = aBool;//just assignment so compiler doesn't optimize my bool out
        }
        if (m.Msg != 0x20a) // Scrolling Message
        {
            return false;//ignore message
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我浮动父表单中包含的用户控件时,不会触发断点.断点被近距离击中,但我可以在用户控件内的实际文本框中,而不是命中.如何准确判断我是否在此用户控件的范围内?

FWIW,我有两台显示器.它似乎与我正在使用的监视器有所不同.

Jay*_*ggs 48

尝试针对您的热门测试,Control.ClientRectangle而不是Control.Bounds:

if (ClientRectangle.Contains(PointToClient(Control.MousePosition))) {
    bool aBool = true;//breakpoint 
    bool two = aBool;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果这是来自`MouseEventArgs`,您甚至可以从中获取`Location`属性,而不使用`PointToClient`. (2认同)