سؤال

How can I detect if a user is holding a certain key?

Using a global KeyDown event would not do the job, because this only triggers at being pressed down, like so:

public MainPage()
{
    this.InitializeComponent();
    Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
}

private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs e)
{
    if (e.VirtualKey == VirtualKey.Right)
    {
        // Logic
    }
}

Is there any way to continuously detect if the key is down or hold? Perhaps in a timer of some sort that checks every milisecond if the key is down?

It could be something like this; however the "right"-variable does not provide with ways to see if it's down. The GetKeyState returns a "CoreVirtualKeyStates". But I can not seem to enumerate through this. According to this link, if the states value is 1, the key is down. But how can I check against this?

If I could check that, the answer would be very easy:

private void MoveTimer_Tick(object sender, object e)
{
    var right = Window.Current.CoreWindow.GetKeyState(VirtualKey.Right);
    if(right == 1)
        // Logic
}

How can I detect if a key is being hold (or continuous down with a timer)?

هل كانت مفيدة؟

المحلول 2

Found my own solution: I can check right against CoreVirtualKeyStates

private void MoveTimer_Tick(object sender, object e)
{
    var right = Window.Current.CoreWindow.GetKeyState(VirtualKey.Right);
    if (right == CoreVirtualKeyStates.Down)
    {
        //Logic
    }
}

This does open up more questions but this issue is resolved.

نصائح أخرى

I think the flag can be set from the key up event:

private void CoreWindow_KeyUp(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs e)
{
    if (e.VirtualKey == VirtualKey.Right)
    {
        right=0
    }
    else
    {
     right=1
    }
}

and thus in your timer your check right flag:

private void MoveTimer_Tick(object sender, object e)
{
    var right = Window.Current.CoreWindow.GetKeyState(VirtualKey.Right);
    if(right == 1)
        // Logic
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top