1

I'm using Visual C# 2015 to develop a WPF project.

I have a Button underneath a Canvas. I'd like to make the Canvas capture all mouse events, so that the Button does not receive any of those events as long as the Canvas is in front. If possible, I'd also like to prevent the Button from receiving any event generated by user input, like KeyDown or MouseMove.

How do I accomplish that?

bot47
  • 1,458
  • 3
  • 18
  • 36

1 Answers1

2

If you want to stop the event propagation, you could use:

private void CanvasEvent(object sender, RoutedEventArgs e)
{
    // Draw/Move stuff
    ...
    e.Handled = true;   
}

in your event handlers. Another approach is to disable the Button or only add it, when it is used. A third approach could be to add a bool flag e.g. isDrawing and in your Button event handler you check the flag.

private void CanvasEvent(object sender, RoutedEventArgs e)
{
    // When drawing etc. starts, where the button should not handle the events
    isDrawing = true;  
}

private void ButtonEvent(object sender, RoutedEventArgs e)
{
    if (isDrawing) { return; }
    // When not drawing do stuff
    ...
}

I would prefer the e.Handled = true; approach. It is necessary to set the Background for the Canvas explicite otherwise it is not hit-testable (see: WPF: Canvas Events Not working).

Community
  • 1
  • 1
wake-0
  • 3,918
  • 5
  • 28
  • 45
  • Unfortunatelly `e.Handled = true` doesn't stop propagation in this scenario and the `isDrawing` approach would still leave the click animation, while disabling the button causes its rendering to be different. – bot47 Feb 27 '17 at 09:55
  • @MaxRied why does `e.Handled = true` not stop the propagation? – wake-0 Feb 27 '17 at 10:02
  • `button` underneath `canvas`. `button.MouseMove: MessageBox.Show("MouseMove");` `canvas.MouseMove: e.Handled = true;` When I move the cursor, the `MessageBox` appears... – bot47 Feb 27 '17 at 10:09
  • try to add the `e.Handled = true` to the `canvas PreviewMouseMove` because the `MouseMove` event is when bubbling up used but you need the tunneling event. – wake-0 Feb 27 '17 at 10:33
  • I'm afraid that makes no difference: `button` underneath `canvas`. `button.MouseMove: MessageBox.Show("MouseMove");` `canvas.PreviewMouseMove: e.Handled = true;` When I move the cursor, the `MessageBox` still appears. – bot47 Feb 27 '17 at 10:59
  • @MaxRied have you explicite set a `Background` for the `Canvas`? – wake-0 Feb 27 '17 at 11:40
  • Yeah, that seems to be the problem. I changed the background to transparent, now it works! – bot47 Feb 28 '17 at 09:55