using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
namespace NameSpace
{
class TextInput
{
public Rectangle TextLoc;
public string Text;
KeyboardState OldState;
public bool Active = false;
private SpriteFont Font;
private Texture2D BackImage;
public Color
[] Colour =
new Color
[2];
int MaxCharacters;
public TextInput(string Default, Rectangle DrawTo, SpriteFont _Font, Texture2D BackGround, Color Active_Colour, Color Static_Colour)
{
Text = Default; TextLoc = DrawTo; Font = _Font; BackImage = BackGround; Colour[0] = Active_Colour; Colour[1] = Static_Colour;
OldState =
new KeyboardState
(); MaxCharacters =
-1;
}
public int Max_Characters
{set { MaxCharacters = value; }}
public int Remaining_Characters
{
get
{
if (MaxCharacters > 0) { return MaxCharacters - Text.Length; }
return 0;
}
}
public void Draw(SpriteBatch SB)
{
int YPos = (int)((TextLoc.Y + (TextLoc.Height / 2)) - (Font.MeasureString("|").Y / 2));
int XPos = (int)((TextLoc.X + (TextLoc.Width / 2)) - (Font.MeasureString(Text).X / 2));
if (Active) { SB.Draw(BackImage, TextLoc, Colour[0]); }
else { SB.Draw(BackImage, TextLoc, Colour[1]); }
SB.
DrawString(Font, Text,
new Vector2
(XPos, YPos
), Color.
Black);
}
public void Update()
{
if (Active)
{
KeyboardState NewState = Keyboard.GetState();
Keys[] PressedKeys = NewState.GetPressedKeys();
foreach (Keys key in PressedKeys)
{
if (OldState.IsKeyUp(key))
{
//Backspace
if (key == Keys.Back) { if (Text.Length > 0) { Text = Text.Remove(Text.Length - 1, 1); } }
//Space
else if (key == Keys.Space) { if (Text.Length > 0) { Text = Text + " "; } }
//Confirm the textbox
else if (key == Keys.Enter) { Active = false; }
//Numbers
else if (key == Keys.D0 || key == Keys.D1 || key == Keys.D2 || key == Keys.D3 || key == Keys.D4 || key == Keys.D5 || key == Keys.D6 || key == Keys.D7 || key == Keys.D8 || key == Keys.D9)
{ string DUD = key.ToString(); Text += DUD.Remove(0, 1); }
//Letters
else if (key == Keys.A || key == Keys.B || key == Keys.C || key == Keys.D || key == Keys.E || key == Keys.F || key == Keys.G || key == Keys.H || key == Keys.I || key == Keys.J || key == Keys.K || key == Keys.L || key == Keys.M || key == Keys.N || key == Keys.O || key == Keys.P || key == Keys.Q || key == Keys.R || key == Keys.S || key == Keys.T || key == Keys.U || key == Keys.V || key == Keys.W || key == Keys.X || key == Keys.Y || key == Keys.Z)
{ try { Text += key.ToString(); } catch { } }
//The rest get ignored as their .ToString()s suck
}
}
OldState = NewState;
if (MaxCharacters > -1 && Text.Length > MaxCharacters)
{ Text = Text.Remove(MaxCharacters, Text.Length - MaxCharacters); }
}
}
}
}