abenci
abenci

Reputation: 8651

How do I know if a arrow key was pressed and not released?

How do I know if a arrow key was pressed and not released? The OnKeyDown event is sent continuously...

EDIT: We would like to get only one notification even if the user keep the botton pressed for minutes.

Thanks.

Upvotes: 1

Views: 205

Answers (3)

Hans Passant
Hans Passant

Reputation: 941317

I'll assume this is a Winforms question, it is not a problem in WPF with the Keyboard class. Keeping track of the KeyDown and KeyUp events isn't reliable, you can miss a notification when your app gains or loses the focus with the key down. You need a bit of pinvoke help:

    public static class NativeMethods {
        public static bool IsKeyDown(Keys key) {
            return GetKeyState(key) < 0;
        }

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern short GetKeyState(Keys key);
    }

Upvotes: 1

stiduck
stiduck

Reputation: 510

You can create a nullable DateTime, and set the current time on your first key down event, and set it to null on the key up event. If the time span is more than a selected value, say one second, then the user is pressing down the key.

Upvotes: 1

dandan78
dandan78

Reputation: 13854

The OnKeyUp event fires when the key is released. OnKeyDown keeps firing because keys repeat when they are held down.

Upvotes: 1

Related Questions