I’m currently writing a developer console for my game, and was wondering how I would get “true” keyboard input.
Basically, I’m currently using a KeyBoardState, and polling it each frame to see which keys have been pressed. This has the issue of missing keys if the user types quite quickly - seeing as it will be mostly me using the console, and I type fast, I find it very annoying.
Plus, when I get around to writing some sort of chat, I’ll need “true” keyboard input then, as well.
One thing you can use is the games Window.TextInput event added in version 3.2. This (from what I know) hooks directly into openTK’s keyboard events, or the low level system hooks in windows. The output argument is a TextInputEventArgs which contains the character entered.
The only downside is that on the OpenGL platform, you need to manually listen for special keys such as backspace and tab via a polling system. What I would recommend is having a method fired by the window, which fires a custom event that takes the TextInputEvent args and simply passes it on. This way when your polling recognizes a special character, it simply fires off the with the special character (ex ‘\t’ or ‘\b’).
In the end, you have a system like this:
EventHandler<TextInputEventArgs> onTextEntered;
KeyboardState _prevKeyState;
...
protected override Initialize()
{
#if OpenGL
Window.TextInput += TextEntered;
onTextEntered += HandleInput;
#else
Window.TextInput += HandleInput;
#endif
}
private void TextEntered(object sender, TextInputEventArgs e)
{
if(onTextEntered != null)
onTextEntered.Invoke(sender, e);
}
private void HandleInput(object sender, TextInputEventArgs e)
{
char charEntered = e.Character;
// Do stuff here
}
protected override void Update(GameTime gameTime)
{
KeyboardState keyState = Keyboard.GetState();
#if OpenGL
if (keyState.IsKeyDown(Keys.Back) && _prevKeyState.IsKeyUp(Keys.Back))
{
_textInput.Invoke(this, new TextInputEventArgs('\b'));
}
if (keyState.IsKeyDown(Keys.Enter) && _prevKeyState.IsKeyUp(Keys.Enter))
{
_textInput.Invoke(this, new TextInputEventArgs('\r'));
}
... // Handle other special characters here (such as tab )
#endif
_prevKeyState = keyState;
}