我正在尝试监听C#应用程序中按下箭头键的事件。
我已经在XAML文件的C#文件中添加了以下方法来监听按下箭头键并报告每个按键:
private void Grid_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Left)
{
Console.WriteLine("left");
}
if (e.Key == Key.Right)
{
Console.WriteLine("Right");
}
if (e.Key == Key.Up)
{
Console.WriteLine("Up");
}
if (e.Key == Key.Down)
{
Console.WriteLine("Down");
}
}
在相应的XAML中,Grid元素如下所示:
<Grid Background="Black" MouseWheel="Grid_MouseWheel"
MouseDown="Grid_MouseDown" MouseUp="Grid_MouseUp"
MouseMove="Grid_MouseMove" KeyDown="Grid_KeyDown">
目前,与鼠标相关的监听器正在运行,但键盘监听器(KeyDown="Grid_KeyDown")无法工作。我需要添加其他内容才能使其正常工作吗?
WpfApplication
中显示Console
窗口?除非您正在运行控制台应用程序并尝试显示Wpf窗口,否则看起来这就是问题所在。如果这是一个测试,请尝试使用System.Diagnostics.Debug.Print
而不是Console.WriteLine
。 - King King