简体   繁体   中英

KeyDown Handling C# / UWP

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM