简体   繁体   中英

wpf extending control with keyboard override

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

    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM