I am writing a calculator for WPF . At the moment, pressing the buttons records data in the textbox , but I would like it to be pressed to the methods when pressing numbers on the keyboard, i.e. so stupid was the interception of buttons. I think it will be too redundant to do it through WinApi , isn’t there any such thing in WPF itself?

  private void One_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "1"; storageVariable += "1"; } private void Two_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "2"; storageVariable += "2"; } private void Three_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "3"; storageVariable += "3"; } private void Four_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "4"; storageVariable += "4"; } 

    1 answer 1

    The easiest way is to subscribe to KeyDown or PreviewKeyDown in the window.

    The delivery order is as follows: first the PreviewKeyDown comes PreviewKeyDown window, then along the chain inside the control that has focus, then the KeyDown control comes along, and up the chain up to the window.

    If you do not need at the window level, pressing the service keys that the TextBox will process (left / right / del), subscribe to KeyDown . PreviewKeyDown also allows you to block text input (for example, you want to prevent the input of the letter A ), and gets everything in a row.

    Example:

     <Window ... PreviewKeyDown="OnPreviewKeyDown"> ... </Window> 
     void OnPreviewKeyDown(object sender, KeyEventArgs e) { var key = e.Key; if (key == Key.A) e.Handled = true; }