Links of Interest
Main
Download
Prerequisites
Screenshots

Articles/Code Snippets
DBP Warmup Entries
Blog feed icon
Contact/Feedback

Quick Downloads:
bullet Diaspora
bullet XNA Requirements Installer

External Links
Heather [layout designer]
XNA

Keyboard Component
This component processes keyboard input. It is not currently a GameComponent, but it can easily be adapted to be one. call KeyboardHelper.Update() in the main game loops before everything else. Also, thanks to Shawn Hargreaves, I have removed a bug where the Keys would get boxed each time they were accessed or added to the dictionary, which resulted in several thousand new objects every second. NOTE: I haven't manually added in all the keys yet. If you wish to use a specific key, add it in the component's Update() method.

Here's how to register the events to use the component:

KeyboardHelper.OnKeyDown += new KeyboardHelper.KeyEventHandler(KeyboardHelper_OnKeyDown);
KeyboardHelper.OnKeyPressed += new KeyboardHelper.KeyEventHandler(KeyboardHelper_OnKeyPressed);
KeyboardHelper.OnKeyUp += new KeyboardHelper.KeyEventHandler(KeyboardHelper_OnKeyUp);

And here is the actual component:

class KeyboardHelper
{
    public delegate void KeyEventHandler(Keys key);
    public static event KeyEventHandler OnKeyPressed;
    public static event KeyEventHandler OnKeyDown;
    public static event KeyEventHandler OnKeyUp;

    static Dictionary<int, bool> keyStates = new Dictionary<int, bool>();

    public static void Update()
    {
        KeyHelper(Keys.Up);
        KeyHelper(Keys.Down);
        KeyHelper(Keys.Left);
        KeyHelper(Keys.Right);
        KeyHelper(Keys.Escape);
        KeyHelper(Keys.Enter);
        KeyHelper(Keys.LeftControl);
        KeyHelper(Keys.Space);

        KeyHelper(Keys.W);
        KeyHelper(Keys.A);
        KeyHelper(Keys.S);
        KeyHelper(Keys.D);
        KeyHelper(Keys.Q);
        KeyHelper(Keys.P);
    }

    static void KeyHelper(Keys key)
    {
        if (!keyStates.ContainsKey((int)key))
            keyStates.Add((int)key, false);
        if (Keyboard.GetState()[key] == KeyState.Down)
        {
            if (!keyStates[(int)key])
                if(OnKeyDown!=null)
                    OnKeyDown(key);
            keyStates[(int)key] = true;
        }
        else
        {
            if (keyStates[(int)key])
                if (OnKeyPressed != null)
                    OnKeyPressed(key);
            if (OnKeyUp != null)
                OnKeyUp(key);
            keyStates[(int)key] = false;
        }
    }
}

This website and its content are the property of ascii reversal of the ascii of the hex reversal of the hex of the bit inverse of 11001111 11001111 11001000 11001010 11000110 11001001 10111100 11001001 10111100 11001001 11000110 11001001 11001110 11001001 10111011 11001001 11001111 11001101 10111100 11001011 11000110 11001001.