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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12520043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:32:22  来源:igfitidea点击:

Detect if cursor is within the bounds of a control

c#winforms

提问by P.Brian.Mackey

I have a user control

我有一个用户控件

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

When I float over the user control contained in a parent form, the breakpoint is not hit. The breakpoint is hit in close proximity, but I can be in an actual textbox inside the user control and not get a hit. How can I accurately determine if I am within the bounds of this user control?

当我浮动在父窗体中包含的用户控件上时,不会命中断点。断点非常接近,但我可以在用户控件内的实际文本框中而不会被击中。如何准确确定我是否在此用户控件的范围内?

FWIW, I have two monitors. It does not appear to make a difference which monitor I am using.

FWIW,我有两个显示器。我使用的显示器似乎没有区别。

采纳答案by Jay Riggs

Try your hit testing against Control.ClientRectanglerather than Control.Bounds:

尝试针对Control.ClientRectangle而不是针对您的命中测试Control.Bounds

if (ClientRectangle.Contains(PointToClient(Control.MousePosition))) {
    bool aBool = true;//breakpoint 
    bool two = aBool;
}

回答by Hamid

just for fast trick, You can trigger all userconrol's control with one event and handle the mouse over events. for example if you had two textbox in your usercontrol

只是为了快速技巧,您可以使用一个事件触发所有用户控制的控件并处理鼠标悬停事件。例如,如果您的用户控件中有两个文本框

    textBox1.MouseMove += new MouseEventHandler(controls_MouseMove);
    textBox2.MouseMove += new MouseEventHandler(controls_MouseMove);
    ...

    void controls_MouseMove(object sender, MouseEventArgs e)
    {
        Control subc=sender as Control;
        int mouseX = MousePosition.X;
        ....
    }