• 13
• 18
• 19
• 27
• 10

# [SlimDX] Keyboard input

This topic is 2894 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I've been using Xna quite alot lately, but I feel the need to learn DirectX programming in C++. Since I haven't written anything in C++ for a long time, I felt that using SlimDX would be a good way to ease myself into DirectX programming, since I won't run into any problems related to C++. Anyways, I've been messing around a bit, and so far I seem to be doing ok, however I can't seem to figure out how to query my Keyboard in "realtime". I'm using Raw Input:
public InputHandler(Game game)
{
this.game = game;

//Register Keyboard & Mouse
Device.RegisterDevice(UsagePage.Generic, UsageId.Keyboard, DeviceFlags.None);
Device.RegisterDevice(UsagePage.Generic, UsageId.Mouse, DeviceFlags.None);

//Events
Device.KeyboardInput += new EventHandler<KeyboardInputEventArgs>(OnKeyboardInput);
}
void OnKeyboardInput(object sender, KeyboardInputEventArgs e)
{
switch (e.Key)
{
case System.Windows.Forms.Keys.A:
if(e.State == KeyState.Pressed)
game.cam.Translate(new Vector3(0.05f, 0, 0));
break;
}
}

This works, but the OnKeyboardInput event doesn't trigger constantly. It triggers once, then there's a half second delay, and then it keeps triggering over and over again (but only a few times per second), the same way as if you'd be holding the key, say in a text editor or something. I don't see any way to query the keyboard state directly whenever I want, which is what I'm used to doing, because it doesn't have this problem. What's the proper way to handle keyboard input in "realtime", for example to make a character walk in a fps game, which needs alot of keyboard updates per second? Thanks, Hyu

##### Share on other sites
Err yeah... I can't believe I didn't manage to find the solution for this last night... it's quite obvious.
The solution is to create a keyboard state yourself.

A Dictionary is quite nice for this:
public class KeyboardState : Dictionary<Keys, bool>{    public KeyboardState()    {        foreach (Keys k in Enum.GetValues(typeof(Keys)))        {            if (!this.ContainsKey(k))                this.Add(k, false);        }    }}

The Device.KeyboardInput event needs to modify the state:
void OnKeyboardInput(object sender, KeyboardInputEventArgs e){    switch (e.State)    {        case KeyState.Pressed:            kbState[e.Key] = true;            break;        case KeyState.Released:            kbState[e.Key] = false;            break;    }}

Now you can query the keyboard state whenever you feel like it.