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