3

based on this thread:

Adding inputbox-like control to XNA game

Not sure if this is a ressurect but i need an input text box for my monogame Project, however im

running the metro app version, any clue on how to get around that? i've been trying already to build

my own gui, but i cant figure out how to limit the text range up the end of the text box image

width, also cant figure out how to move the current text index to an earlier point with the left

arrow or farther with the right arrow keyboard key, can anyone possibily help me out with this?

thanks in advance for any help! Kind regards, Romulo Romero

Community
  • 1
  • 1
Ogre3dUser
  • 79
  • 1
  • 3
  • 10

1 Answers1

2

I'm assuming you want a single line textbox - which is quite a bit easier than multiline, as you don't need word wrapping - and you have key and character input figured out.

I have not worked with monogame, but I made an input box for xna not too long ago, so I hope this will help.

What you want to do is define a background rectangle (could also be an image), and remember the text cursor (also called I-beam pointer) position. This is after which character of the text the cursor is, and where you'll input newly entered characters. So now in code, here are the variables you'll need in your Textbox class (assuming you will use a class for that, which would be the easiest):

string text = ""; //Start with no text
int cursorPos = 0;
//These are set in the constructor:
SpriteFont font;
Rectangle backRect;

Now you can start handling character input. Whenever a character is entered you want to insert that at the cursor position. But you also want to check if the new text is no longer than the width of the back rectangle, so this is what the code for that will look like:

public void CharEntered(char c)
{
    string newText = text.Insert(cursorPos, c.ToString()) //Insert the char

    //Check if the text width is shorter than the back rectangle
    if (font.MeasureString(newText).X < backRect.Width)
    {
        text = newText; //Set the text
        cursorPos++; //Move the text cursor
    }
}

All you have to do now is handle key input, and change the cursorPos when the left or right arrow key is pressed. And drawing the text etc, but that stuff is pretty simple ;)

Hope this helped! ~Luca

Luca_Scorpion
  • 371
  • 4
  • 15