KeyDown Handling C# / UWP

2019-08-21 06:11发布

I'm Trying to make app send a pulse to a relay. I got it done with a Button_click, but now I want to do it with any keystroke. What Can I use for this? I read about KeyDown but I don't really know how to integrate it, Any help would be much appreciated. Thank you in advance!

Here is how my code looks like:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (relay_state == 0)
        {
            relayPin.Write(GpioPinValue.Low);
            relay_state = 1;
        }
        else if (relay_state == 1)
        {
            relayPin.Write(GpioPinValue.High);
            relay_state = 0;
        }

标签: c# uwp keydown
1条回答
我命由我不由天
2楼-- · 2019-08-21 07:09

You can add KeyDown event listener to your page:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    CoreWindow.GetForCurrentThread().KeyDown += Page_KeyDown;
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    CoreWindow.GetForCurrentThread().KeyDown -= Page_KeyDown;
}

private void Page_KeyDown(CoreWindow sender, KeyEventArgs args)
{
    //Do your stuff here!
    System.Diagnostics.Debug.WriteLine("Pressed Key");
}
查看更多
登录 后发表回答