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".
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".
You don't need to use the
.ToString()
function to find out what key(s) are pressed.You need to track the
KeyboardState
in order to find out which key(s) are/were pressed. e.g.I don't know if C# 7 will allow pattern matching like this but other F# users might also look for something like this like I did.
I know this is answered already, but I found this topic here, and did a little refactoring in some code there:
It's important to note that I needed a reference to windows.forms for the upper case stuff(I'm sure there's a better way, but i'm in a hurry here so :P )
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.
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.
I spent some time writing this for one of my projects. Have a look over it I think one of the keys may be wrong but here it is.
There are two methods - GetKeyFromString(string keyStr) and GetStringFromKey(Keys key) and you can call them from anywhere like