KeyDown Handling C# / UWP

2019-08-21 06:15发布

问题:

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;
        }

回答1:

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");
}


标签: c# uwp keydown