Search code examples
c#openglopentk

OpenTK keypress?


I'm looking for a cross platform (Win & MacOS) method to detect keypresses in C# for an OpenGL application.

The following works, but for alphanumeric characters only.

protected override void OnKeyPress(OpenTK.KeyPressEventArgs e)
{
    if (e.KeyChar == 'F' || e.KeyChar == 'f')
        DoWhatever();
}

Currently, I'm hacking it, detecting when the user releases a key:

void HandleKeyUp (object sender, KeyboardKeyEventArgs e)
{
    if (e.Key == Key.Tab)
        DoWhatever();
}

Using OpenTK.Input, I can test if a key is being held, but I'm after the initial keypress only.

var state = OpenTK.Input.Keyboard.GetState();

if (state[Key.W])
    DoWhatever();

So, what approaches are OpenTK users taking to register keypresses?

SOLUTION

As suggested by Gusman, simply by comparing the current keyboard state to that of the previous main loop.

KeyboardState keyboardState, lastKeyboardState;

protected override void OnUpdateFrame(FrameEventArgs e)
{
    // Get current state
    keyboardState = OpenTK.Input.Keyboard.GetState();

     // Check Key Presses
    if (KeyPress(Key.Right))
            DoSomething();

    // Store current state for next comparison;
    lastKeyboardState = keyboardState;
}

public bool KeyPress(Key key)
{
    return (keyboardState [key] && (keyboardState [key] != lastKeyboardState [key]) );
}

Solution

  • Change a bit your mind and you will see it clear.

    You're programming an OpenGL application, so you have a main loop where you update and render your objects.

    If in that loop you get the keyboard state and compare to the previous stored state you have all the keyboard changes, then it's very easy to fire your own events (or just call functions) with the key changes.

    In this way you will use the inherent mechanism to OpenTK and will be 100% portable.