I'm having difficulties creating an inputbox with XNA 4.0.
I can already draw and input text into the inputTextbox, but when I type I have two problems occuring.
Here is the code which belongs to the textbox:
public TextboxInput(GraphicsDevice graphicsDevice, int width, SpriteFont font)
{
this.font = font;
var fontMeasurements = font.MeasureString("dfgjlJL");
var height = (int) fontMeasurements.Y;
renderTarget = new RenderTarget2D(graphicsDevice, width, height);
Text = new StringBuilder();
this.graphicsDevice = graphicsDevice;
spriteBatch = new SpriteBatch(graphicsDevice);
}
public void Update(GameTime gameTime)
{
if (!HasFocus)
{
return;
}
var keyboard = Keyboard.GetState();
foreach (var key in keyboard.GetPressedKeys())
{
if (!lastKeyboard.IsKeyUp(key))
{
continue;
}
if (key == Keys.Delete ||
key == Keys.Back)
{
if (Text.Length == 0)
{
continue;
}
Text.Length--;
renderIsDirty = true;
continue;
}
char character;
if (!characterByKey.TryGetValue(key, out character))
{
continue;
}
if (keyboard.IsKeyDown(Keys.LeftShift) ||
keyboard.IsKeyDown(Keys.RightShift))
{
character = Char.ToUpper(character);
}
Text.Append(character);
renderIsDirty = true;
}
lastKeyboard = keyboard;
}
public void PreDraw()
{
if (!renderIsDirty)
{
return;
}
graphicsDevice.Clear(BackgroundColor);
renderIsDirty = false;
graphicsDevice.SetRenderTarget(renderTarget);
spriteBatch.Begin();
spriteBatch.DrawString(font, Text, Vector2.Zero, ForegroundColor);
spriteBatch.End();
graphicsDevice.SetRenderTargets(null);
}
public void Draw()
{
spriteBatch.Begin();
spriteBatch.Draw(renderTarget, Position, Color.White);
spriteBatch.End();
}
For the flicker, I think that you should be calling graphicsDevice.Clear(BackgroundColor) in your draw method.
The following code is the reason you don't get more characters when holding down. It is saying only register the key press if the keys last state was up.
if (!lastKeyboard.IsKeyUp(key))
{
continue;
}