我正在开发这个应用程序,它需要在应用程序获得焦点时读取每个击键。
除了 3 个键:空格键、Enter 键和退格键,我可以读取所有键。
这是我项目的代码片段:
XAML 文件:
<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 文件:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return || e.Key == Key.Space)
MessageBox.Show("" + e.Key);
}
最佳答案
使用 PreviewKeyDown 代替 KeyDown,您就完成了 -
<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" />
关于c# - 键盘按键捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5687897/