键盘按键捕获

3

我正在开发一个应用程序,需要在应用程序聚焦时读取每个按键。

我可以读取除空格键、回车键和退格键之外的所有按键。

这是我的项目中的代码片段:

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);
}
2个回答

2
使用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" />


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接