0

I'm extending the control canvas and adding my own custom overrides for MouseEvents. I was curious to know why this basic override which is when the user presses any key on the keyboard it doesn't emit a signal. How can I make this override work in wpf c#?

namespace CanvasGraphDemo
{
    public class CanvasGraph : Canvas
    {
        public CanvasGraph()
        {
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (e.Key == Key.Enter)
            {
                Console.WriteLine("context menu open");
                e.Handled = true;
            }
        }

    }
}
JokerMartini
  • 5,674
  • 9
  • 83
  • 193

1 Answers1

3

This will work with your specific example. As others noted, you have to make the Canvas focusable and actually focus it, so it will receive keyboard events.

public class CanvasGraph : Canvas
{
    public CanvasGraph()
    {
        Focusable = true;
        Loaded += OnCanvasGraphLoaded;
    }

    private void OnCanvasGraphLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        Focus();
        Loaded -= OnCanvasGraphLoaded;
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        if (e.Key == Key.Enter)
        {
            Console.WriteLine("context menu open");
            e.Handled = true;
        }
    }
}
Szabolcs Dézsi
  • 8,743
  • 21
  • 29