Event driven input on the PC

XNA has a rather severe limitation with regards to handling keyboard input. It is unable detect any keystrokes that occur between pollings. Because of this if your game is updating at the default 60 fps there are 0.017 seconds between polls can be too slow for individual characters of memorized sequences such as "ing". This method also has the advantage of behaving consistently with other applications, the double click time, character repeat time, etc... are all controlled by your windows settings.

To solve this I used a class created by leidegren.se that processes the Windows messages directly and is very easy to incorporate into your project. This post is to help you get set up and serve as a reference should you need it. Feel free to post any quirks you run into and I'll add them.

To set it up, call the below.


After initializing the hook there are 9 events that it will trigger. The names are very self explanatory so I'm only going to talk about a few of the quirks I have come across.

//Keyboard Events
event CharEnteredHandler CharEntered;  
event KeyEventHandler KeyDown;  
event KeyEventHandler KeyUp;

//Mouse Events
event MouseEventHandler MouseDown;  
event MouseEventHandler MouseUp;  
event MouseEventHandler MouseMove;  
event MouseEventHandler MouseHover;  
event MouseEventHandler MouseWheel;  
event MouseEventHandler MouseDoubleClick;

void CharEnteredHandler(object sender, CharacterEventArgs e);  
void KeyEventHandler(object sender, KeyEventArgs e);  
void MouseEventHandler(object sender, MouseEventArgs e);  

CharEntered returns everything that is a character including returns, backspace characters, and the like. Also keyboard combinations such as Ctrl + C are represented as a single character which can be compared by casing the integer value of the character (for example Ctrl + x == (char)3). CharEntered repeats if the corresponding key is healed down, a behavior very useful for text boxes and the like.

comments powered by Disqus