Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MonoGame Key Pressed String

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".

like image 707
Evorlor Avatar asked Dec 26 '22 11:12

Evorlor


2 Answers

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.

like image 62
craftworkgames Avatar answered Dec 28 '22 08:12

craftworkgames


Too little rep to comment but if you only want to allow A-Z as input and you're using Monogame (and XNA maybe) you can look at the Keys enum and see if the key value you're testing for is within that range.

Something along the lines of

if((int)key > 64 && (int)key <  91)
   {
      keyValue = key.ToString();
      this.EnteredString += keyValue;
   }

Where 64 is the key below A in the enum and 91 is the key above z in the enum :)

You can allow numbers with the same idea :

else if ((int)key > 47 && (int)key < 58)
     {
     keyValue = key.ToString();
     keyValue = keyValue.TrimStart('D');

     this.EnteredString += keyValue;
     }

and will trim the unwanted "D" character which shows up

like image 31
propellerhat23 Avatar answered Dec 28 '22 10:12

propellerhat23