在窗口中按下“空格”键时调用函数

时间:2014-12-18 20:40:00

标签: wpf

我开发了一个棋盘游戏,我希望在窗口按下 space 时调用一个函数,但在搜索过程中我无法找到问题的答案。 你有什么想法吗?

2 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。最简单的是挂钩一个事件处理程序(尽管不是最优雅的)。也可以使用涉及命令的更优雅的解决方案,具体取决于您使用的控件。

XAML

<Window KeyDown="MainWindow_OnKeyDown"
        <!-- other properties -->
>
    <!-- rest of your UI -->
</Window>

背后的代码

private void MainWindow_OnKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Space)
    {
        // do something  
    }
}

答案 1 :(得分:0)

XAML:

<Window ...
        PreviewKeyUp="Window_PreviewKeyUp" >


</Window>

代码背后:

// Use the PreviewKeyUp event to capture the keypress before 
// any child controls that have focus handle the event
private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
{
    if(e.Key == Key.Space)
    {
        AFunction(); 
        // to prevent the key press to bubble up to child controls that have focus
        e.Handled = true; 
    }
}
相关问题