How can I capture KeyDown event on a WPF Page or UserControl object?

Attach to the Window’s Event

After the control is loaded, attach to the Window’s KeyDown event (or any event) by using Window.GetWindow(this), like so:

The XAML

<UserControl Loaded="UserControl_Loaded">
</UserControl>

The Code Behind

private void UserControl_Loaded(object sender, RoutedEventArgs e) {
  var window = Window.GetWindow(this);
  window.KeyDown += HandleKeyPress;
}

private void HandleKeyPress(object sender, KeyEventArgs e) {
  //Do work
}

Leave a Comment