3

I`m developing this application that need to read every key stroke while the application is focused.

I can read all keys except for 3 keys: Space bar, Enter and backspace.

This is a code snippet form my project:

XAML File:

<TextBox Height="108" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="354" AcceptsReturn="True" AcceptsTab="True" KeyDown="textBox1_KeyDown" IsReadOnly="False" IsEnabled="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" />

CS File:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return || e.Key == Key.Space)
        MessageBox.Show("" + e.Key);
}
sikas
  • 5,435
  • 28
  • 75
  • 120

2 Answers2

2

Instead of KeyDown use PreviewKeyDown and your done -

<TextBox Height="108" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="354" AcceptsReturn="True" AcceptsTab="True" PreviewKeyDown="textBox1_KeyDown" IsReadOnly="False" IsEnabled="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" />
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
0

See this Link WPF: OnKeyDown() not being called for space key in control derived from WPF TextBox.

Community
  • 1
  • 1
Nighil
  • 4,099
  • 7
  • 30
  • 56