This is the WPF calculator code.

Example method for the button (btn 1)

private void btn1_Click(object sender, RoutedEventArgs e) { KeyAll(1); } //----------------------------------------------------------------- void KeyAll(int enter) { if (operation == "") { number1 = (number1 * 10) + enter; txtDisplay.Text = number1.ToString(); } else { number2 = (number2 * 10) + enter; txtDisplay.Text = number2.ToString(); } } //-------------------------------------------------------------------- private void Grid_PreviewKeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.NumPad1: KeyAll(1); break; //и так далее 

I tried through (KeyDown through PreviewKeyDown) I tried to subscribe to the event both to the button and at the Grid level.
I click the mouse - it works. I click on the keyboard - it works, but only if before that you click on any digit with the mouse.

  • Perhaps the focus is not on that grid, so it does not work. Handle keystrokes in window events, not grid. - Andrey NOP
  • @Andrey NOP You mean here <Button x:Name="btn1" Grid.Row="4" Grid.Column="0" FontSize="30" Click="btn1_Click" >1</Button> or at the level <Grid.ColumnDefinitions> <ColumnDefinition/> In general, I tried it there and there. I understand the focus on txtDisply, but I don’t understand how to transfer it to button 1 for example. ` - j. Atisto
  • 3
    I mean to subscribe not to Grid.PreviewKeyDown , but to Window.PreviewKeyDown - Andrey NOP
  • @ Andrei NOP Thank you, it works! - j. Atisto

1 answer 1

Most likely, your Grid has no focus when you press a key, and when you click the button with the mouse, you put the focus and everything starts working as it should.

The solution is to handle keystroke events at the root element itself - at the window. Those. Grid.PreviewKeyDown not to Grid.PreviewKeyDown , but to Window.PreviewKeyDown