Johny P. Johny P. - 2 months ago 9
C# Question

Create an in-game TextBox

So I am trying to implement username system into my game and to do so I need to let the user input their desired username. I created a

TextBox
class.

EDIT

Upon making a further research on other people's experience with the creation of a
TextBox
in-game, and their approach I came to the following conclusions:


  • My current code is badly designed because the
    Microsoft.Xna.Framework.Input.Keys
    and
    Microsoft.Xna.Framework.Input.KeyboardState.GetState()
    were never supposed to be used like this.

  • Because of that, the code is inefficient and would consume huge time and effort to do things that are otherwise insignificant because Windows handles them for you, when using
    Winforms
    . I will try to find a possible solution by working with some Win32 functions from the
    user32.dll
    . And probably use
    regexp
    to validate strings.



Once I have it figured out, I'm going to revisit the current code and see what I can recycle and then, scrap the rest.

Answer

I think the input problem is here:

if (MainGame.InputManager.IsKeyPressed(keys))
{
    keys = MainGame.InputManager.PressedKeys;

If I understand correctly, this literally reads "if any of the keys pressed last frame is pressed, then do check for input", which is always false. Removing the if statement should solve the problem in that case.

I don't quite follow how the StringBuilder is used. StringBuilder is meant for string modification with low garbage generation, but you're negating that by calling ToString and updating a duplicate string on every key press. Also, if the string length exceeds maximum length, you're truncating the displayed final string but not content, getting them out of sync. I'd just go with modifying final directly.

Detecting alphanumeric characters is easiest done with char.IsLetterOrDigit.

You can also look into GameWindow.OnTextInput if you want to replicate WinForms behavior.

Comments