MonoGame Key Pressed String

Evorlor picture Evorlor · Mar 21, 2014 · Viewed 7.1k times · Source

In MonoGame, how can I read which keyboard key is pressed in the form of a String?

I have tried String pressedKey = Keyboard.GetState().ToString();, but it gives me "Microsoft.Xna.Framework.Input.KeyboardState".

Answer

craftworkgames picture craftworkgames · Mar 22, 2014

In games, you typically think of keys as buttons that have state rather than strings because you are usually checking if a button is up or down to move a character around, shoot, jump, etc.

As others have said, you said you should use IsKeyDown and IsKeyUp if you already know what keys you want to test. However, sometimes you just want to know what keys are being pressed. For that, you can use the GetPressedKeys method which will give you an array of keys currently pressed on the keyboard.

If you wanted to turn those keys into a string, you could probably do something like this in your update method.

    private string _stringValue = string.Empty;

    protected override void Update(GameTime gameTime)
    {
        var keyboardState = Keyboard.GetState();
        var keys = keyboardState.GetPressedKeys();

        if(keys.Length > 0)
        {
            var keyValue = keys[0].ToString();
            _stringValue += keyValue;
        }

        base.Update(gameTime);
    }

However, keep in mind that this won't be perfect. You'd have to add extra code to handle the SHIFT key for upper and lowercase letters and you would want to filter out other keys like Ctrl and Alt. Perhaps restrict the input to only alphanumeric values and so on..

Good luck.