P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

Detect if cursor is within the bounds of a control

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.

Upvotes: 22

Views: 37207

Answers (2)

Jay Riggs
Jay Riggs

Reputation: 53593

Try your hit testing against Control.ClientRectangle rather than Control.Bounds:

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

Upvotes: 60

Hamid
Hamid

Reputation: 827

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

Upvotes: -3

Related Questions