richardjmoss's picture

Delaying repeating keypresses in OnUpdateFrame


I'm just getting started with OpenTK, and so far I'm making nice progress albeit with a fair few ups and downs. I have basic 2D rendering working nicely and was trying to plug in keyboard support to alter the state of the prototype when I hit an issue.

I'm using the default implementation of GameWindow, where OnUpdateFrame is called 30 times a second, and no limit on OnRenderFrame.

First I tried using OnUpdateFrame to alter state - I added a check for the spacebar, and performed an action if it was pressed. However, the simple act of pressing and releasing the space bar is picked up in at least half a dozen OnUpdateFrame events, thus performing the action multiple times. Very undesirable! (Unless you want your game character to move at warp speed I suppose.)

Next I tried hooking into the KeyDown event of the Keyboard class. This worked, and I only received a single state change. Unfortunately there doesn't seem to be any form of repeating, so the event is called exactly once. Same with KeyUp. Therefore if you hold the keydown, you only ever receive one notification.

So I guess I still need to make use of OnUpdateFrame but somehow only process key presses after a certain length of time has passed since the last keypress / repeat. So for example, if I press space once, I get one state change. If I hold space down, I get regular (say once every half second) state changes.

Hopefully the above makes some sort of sense. Is there anything built into OpenTK that can help me with this? Or does anyone have any suggestions on how best to do this?

Richard Moss


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
the Fiddler's picture

Try setting KeyRepeat to true:


If KeyRepeat is true, multiple KeyDown events will be generated while a key is being held. Otherwise only one KeyDown event will be reported.

The rate of the generated KeyDown events is controlled by the Operating System. Usually, one KeyDown event will be reported, followed by a small (250-1000ms) pause and several more KeyDown events (6-30 events per second).

Set to true to handle text input (where keyboard repeat is desirable), but set to false for game input.

richardjmoss's picture

Thanks for the response. I had a look at this but then realized then I'm approaching this the wrong way, as I would probably need to control the exact interval between repeat presses rather than what the operating system repeat rate is. At the moment I'm doing some elapsed time checking which is working but unwieldy for one key code let alone multiple codes.