3

I'm developing a quick app to get to grips with Xamarin/Monogame for android and I've hit a snag. There's a point where I need players to be able to enter some character names and have figured out how to cause the Android Soft Keyboard to show up when they click on a 'text box' I've draw onto the game's canvas. I use the method here to do it, and that works fine.

However, none of the keyboard input seems to be going through. Admittedly my name input code is a bit cobbled together to make my 'text box' work, but even something as simple as "if any key is pressed, exit the program" isn't triggering. Does anybody know how to fix this issue?

This is the code I have so far to take in input and store it into the nameInput variable (which is used to store the character name when submitted, and also to show the text in the text box for the player as it's being typed)

private void GetKeys()
{
    KeyboardState kbState = Keyboard.GetState();
    Keys[] pressedKeys = kbState.GetPressedKeys();

    //check if any of the previous update's keys are no longer pressed
    foreach (Keys key in lastPressedKeys)
    {
        if (!pressedKeys.Contains(key))
            OnKeyUp(key);
    }

    //check if the currently pressed keys were already pressed
    foreach (Keys key in pressedKeys)
    {
        if (!lastPressedKeys.Contains(key))
            OnKeyDown(key);
    }
    //save the currently pressed keys so we can compare on the next update
    lastPressedKeys = pressedKeys;
}

private void OnKeyDown(Keys key)
{
    //do stuff
    if (key == Keys.Back && nameInput.Length > 0) //Removes a letter from the name if there is a letter to remove
    {
        nameInput = nameInput.Remove(nameInput.Length - 1);
    }
    else if (key == Keys.LeftShift || key == Keys.RightShift)//Sets caps to true if a shift key is pressed
    {
        caps = true;
    }
    else if (!caps && nameInput.Length < 16) //If the name isn't too long, and !caps the letter will be added without caps
    {
        if (key == Keys.Space)
        {
            nameInput += " ";
        }
        else
        {
            nameInput += key.ToString().ToLower();
        }
    }
    else if (nameInput.Length < 16) //Adds the letter to the name in CAPS
    {
        nameInput += key.ToString();
    }
    else if (key == Keys.Enter)
    {
        HideKeyboard();
    }
}

private void OnKeyUp(Keys key)
{
    //Sets caps to false if one of the shift keys goes up
    if (key == Keys.LeftShift || key == Keys.RightShift)
    {
        caps = false;
    }
}
highboi
  • 673
  • 7
  • 28
DysNihil
  • 31
  • 1

0 Answers0