Search code examples
wpfeventscanvasmousemoveonmousemove

C# WPF - Canvas MouseMove event firing even when mouse moves over child control


How to make it so the Canvas MouseMove event only fires if my mouse is over the Canvas and the Canvas only?

I have a TextBox as a child of the Canvas and it still fires when my mouse is moving over that TextBox, i would like this to not happen, it should only fire when the mouse is moving over the Canvas background/blank space for example.


Solution

  • How to make it so the canvas MouseMove event only fires if my mouse is over the Canvas and the Canvas only?

    You can't prevent the event from being fired but you can check whether the mouse is directly over the Canvas area in your event handler and simply do nothing if it isn't:

    private void Canvas_MouseMove(object sender, MouseEventArgs e)
    {
        if (Mouse.DirectlyOver == sender)
        {
            //your code...
        }
        //else, i.e. when the mouse moves over the TextBox or another child element, do nothing
    }