LogoLogo
  • Gum Tool
    • Introduction
    • Setup
      • Running from Source
    • Showcase
    • Tutorials and Examples
      • Intro Tutorials
        • 1 - The Basics
        • 2 - Variables Tab
        • 3 - Files
        • 4 - Components
        • 5 - Exposing Variables
        • 6 - Parent
        • 7 - States
        • 8 - State Categories
      • Animation Tutorials
        • 1 - Introduction to Animation
        • 2 - Creating an Animation
        • 3 - Playing Animations inside other Animations
        • 4 - Combining Multiple Categories
      • Examples
        • Bottom-Up Stack
        • Centering
        • Custom NineSlice
        • Health Bar
        • Padding
    • Gum Elements
      • General Properties
        • Alpha
        • Base Type (Inheritance)
        • Blend
        • Clips Children
        • Has Events
        • Height Units
        • Ignored By Parent Size
        • Locked
        • Max Height
        • Max Width
        • Min Height
        • Min Width
        • Order
        • Parent
        • Rotation
        • Visible
        • Variable References
        • Width Units
        • X
        • X Origin
        • X Units
        • Y
        • Y Origin
        • Y Units
      • Behaviors
        • Default Implementation
      • Circle
      • ColoredRectangle
      • Component
        • Default Child Container
      • Container
        • Children Layout
        • Contained Type
        • Is Render Target
        • Stack Spacing
        • Wraps Children
      • NineSlice
        • Blend
        • Custom Frame Texture Coordinate Width
        • Texture Address
        • Texture Left
        • Texture Top
      • Polygon
        • Points
      • Skia Standard Elements
        • General Properties
          • Has Dropshadow
          • Is Filled
          • Use Gradient
        • Arc
          • Start Angle
          • Sweep Angle
          • Thickness
        • Canvas
        • ColoredCircle
        • LottieAnimation
        • RoundedRectangle
          • Corner Radius
        • Svg
      • Sprite
        • Color
        • Source File
        • Texture Address
        • Wrap
      • States
        • Categories
      • Text
        • Blue
        • Color
        • Font
        • Font Scale
        • Font Size
        • Green
        • Is Bold
        • Is Italic
        • MaxLettersToShow
        • Outline Thickness
        • Red
        • Text
        • Text Overflow Horizontal Mode
        • Text Overflow Vertical Mode
        • Use Custom Font
        • Use Font Smoothing
    • Project Tab
    • Code Tab
      • Runtime Generation Details
      • Generation Scope
      • Inheritance Location
      • Is CodeGen Plugin Enabled
      • Show CodeGen Preview
    • Localization
    • Menu
      • Content
      • Project Properties
    • Plugins
      • AddAndRemoveVariablesForType
      • AddMenuItem
      • Export
      • Setting Up Post Build Events
    • Variables
      • Add Variable
    • Bitmap font generator (.fnt)
    • Upgrading
      • Migrating 2025 April 27 to Preview
      • Breaking Changes
        • Removal of Variable Spaces
  • Code
    • Gum Code Reference
      • AnimationRuntime
      • BitmapCharacterInfo
      • BitmapFont
      • Camera
      • CircleRuntime
      • ColoredRectangleRuntime
      • Component Runtimes
      • ContainerRuntime
      • Cursor
      • Gum Class Overview
      • DataUiGrid
        • Reflection
        • Categories
      • ElementSave
        • ToGraphicalUiElement
      • GraphicalUiElement
        • Absolute Values
        • AddToManagers
        • AnimateSelf
        • ApplyState
        • BlendState
        • CanvasHeight
        • CanvasWidth
        • Children
        • ContainedElements
        • Font Values
        • GetAbsoluteHeight
        • GetAbsoluteWidth
        • GetChildByNameRecursively
        • GetFrameworkElementByName
        • IsAllLayoutSuspended
        • Parent
        • RemoveFromManagers
        • UpdateLayout
      • GumProjectSave
      • IDataUi
      • InstanceMember
      • InstanceSave
      • InteractiveGue
        • CurrentInputReceiver
        • RaiseChildrenEventsOutsideOfBounds
        • RollOverBubbling
      • IPositionedSizedObject
      • Layer
      • NineSliceRuntime
      • RectangleRuntime
      • Renderer
        • SinglePixelTexture
      • SelectedState
      • SpriteRenderer
        • LastFrameDrawStates
      • SpriteRuntime
        • TextureAddress
        • TextureHeight
        • TextureLeft
        • TextureTop
        • TextureWidth
      • TextRuntime
        • Color
        • FontScale
        • FontSize
        • HorizontalAlignment
        • Text Wrapping
        • VerticalAlignment
      • VariableSave
    • FNA
    • Kni
    • Meadow
    • MonoGame
      • Setup
        • Linking Game Project to Source (Optional)
      • Tutorials
        • Gum Project Forms Tutorial
          • Setup
          • Gum Screens
          • Common Component Types
          • Styling
          • Multiple Screens
        • Code-Only Gum Forms Tutorial
          • Setup
          • Forms Controls
          • ListBox Items
          • Input in Forms
        • [Deprecated] Gum Project (.gumx) Tutorial
          • Setup
          • Gum Screens
          • Gum Forms
          • Customizing Forms
          • Strongly Typed Components Using Code Generation
          • Multiple Screens
      • Setup for GumBatch (Optional)
      • Loading a Gum Project (Optional)
      • async Programming
      • Custom Runtimes
      • GumBatch
      • Gum Forms
        • Binding (ViewModels)
        • Controls
          • Button
          • CheckBox
          • FrameworkElement
            • BindingContext
            • IsEnabled
            • IsFocused
            • ModalRoot and PopupRoot
            • SetBinding
          • ListBox
          • ListBoxItem
          • MenuItem
          • PasswordBox
          • RadioButton
          • ScrollViewer
            • VerticalScrollBarValue
          • StackPanel
          • Slider
          • TextBox
        • Control Customization In Code
          • MenuItem
        • Control Customization in Gum Tool
        • Gamepad Support
        • Keyboard Support
        • Troubleshooting
      • File Loading
      • Resizing the Game Window
      • Known Issues
      • Samples
        • MonoGameGumFormsSample
    • Nez
    • Silk.NET
    • SkiaGum
      • Setup
        • WPF
    • .NET MAUI
      • Setup
Powered by GitBook
On this page
  • Code Example: Creating a TextBox
  • Typing
  • PreviewTextInput
  • IsReadOnly
  • Selection
  • CaretIndex
  • TextWrapping
  • Extended Character Sets and Keyboards

Was this helpful?

Edit on GitHub
Export as PDF
  1. Code
  2. MonoGame
  3. Gum Forms
  4. Controls

TextBox

The TextBox control allows users to enter a string. It supports highlighting, copy/paste, selection with mouse and keyboard, and CTRL key for performing operations on entire words.

Code Example: Creating a TextBox

The following code creates a TextBox.

var panel = new StackPanel();
panel.Spacing = 5;
panel.AddToRoot();

var textBox = new TextBox();
textBox.X = 50;
textBox.Y = 50;
textBox.Width = 200;
textBox.Height = 34;
textBox.Placeholder = "Placeholder Text...";
panel.AddChild(textBox);

var textBox2 = new TextBox();
textBox2.X = 50;
textBox2.Y = 90;
textBox2.Width = 200;
textBox2.Height = 34;
textBox2.Placeholder = "Placeholder Text...";
panel.AddChild(textBox2);

Typing

TextBox supports reading characters from the keyboard. It supports:

  • Regular character typing - inserts a character the the caret position (CaretIndex)

  • Backspace - removes a character at the index before the caret

  • Delete - removes a character at the caret index

  • Enter (if multi-line) - inserts the newline character ('\n')

  • Keyboard repeat rate - if a key is held, the repeat rate applies according to the OS settings

  • CTRL X, C, and V for cut, copy, and paste

The TextBox respects the OS-level repat rate. For example, the following animation shows the TextBox responding to the Windows Key repeat rate.

PreviewTextInput

The PreviewTextInput event is raised whenever text is added to a text box. This includes regular typing and also pasting. This method can be used to react to text before it has been added to the TextBox.

The event includes arguments with a Handled property. Setting this to true prevents the Text from being added to the TextBox. The argument's Text property contains the newly-added text. Keep in mind this can be a longer string if the user has pasted text, so you may need to check all letters rather than only the first.

For example, the following code shows how to only allow numbers in a TextBox:

var label = new Label();
panel.AddChild(label);

var textBox = new TextBox();
textBox.PreviewTextInput += (sender, args) =>
{
    label.Text = "Handling text " + args.Text;
    if (args.Text.Any(item => !char.IsDigit(item)))
    {
        args.Handled = true;
    }
};
panel.AddChild(textBox);

IsReadOnly

If IsReadOnly is set to true, then the user cannot modify a TextBox's Text. Setting IsReadOnly to true results in the following TextBox behavior:

  • Text cannot be changed by typing, pasting, cutting, or deleting text with the keyboard

  • Text can be selected with the mouse or with key combinations (shift + arrow key)

  • Text can be copied

  • The TextBox can receive focus

  • The Caret is optionally visible depending on whether IsCaretVisibleWhenReadOnly is set to true. By default IsCaretVisibleWhenReadOnly is false.

The following code shows how to create a read-only TextBox:

var textBox = new TextBox();
textBox.Width = 200;
textBox.IsReadOnly = true;
textBox.Text = "This is read-only text";
panel.AddChild(textBox);

Selection

Selection can be performed programmatically or by the user using the cursor.

The SelectionLength property can be used to determine if any text is selected. The following code shows how to output the selected characters:

if(textBox.SelectionLength > 0)
{
    var selectedText = textBox.Text.Substring(
        textBox.SelectionStart, 
        textBox.SelectionLength);
    System.Diagnostics.Debug.WriteLine("Selected text: " + selectedText");
}

The SelectionStart and SelectionLength properties can be modified to change the visual selection. For example, the following selects the first 5 letters:

textBox.SelectionStart = 0;
textBox.SelectionLength = 5;

The entire text can be selected as shown in the following code:

textBox.SelectionStart = 0;
textBox.SelectionLength = textBox.Text?.Length ?? 0; // in case text is null

Selection can also be performed by the user. Double-clicking the text box selects all text. Also, pressing CTRL+A selects all text.

A push+drag with the mouse selects the text between the start and the current location of the drag.

Holding down the shift key and pressing the arrow keys adjusts the selection.

CaretIndex

CaretIndex returns the index of the caret where 0 is before the first letter. This value is updated automatically when letters are typed, the caret is moved with arrow/home/end, and when the cursor is clicked and the cursor is moved.

The user can modify the CaretIndex using the following actions:

  • Clicking in the text box places the caret at the nearest index to the click point

  • Typing text moves the caret to the right by one character

  • Pasting text moves the caret to the end of the pasted text

  • Left arrow and right arrow on the keyboard moves the caret to the left or right by one index

  • CTRL + left arrow and CTRL + right arrow move the caret to the left or right by one word

  • Home key moves the caret to the beginning of the line

  • End key moves the caret to the end of the line

CaretIndex can be explicitly set in code to move the caret position.

When CaretIndex changes the CaretIndexChanged event is raised.

The following code shows how to display the CaretIndex in a label:

var panel = new StackPanel();
panel.AddToRoot();

var label = new Label();
panel.AddChild(label);

var textBox = new TextBox();
textBox.TextWrapping = TextWrapping.Wrap;
textBox.Height = 140;
panel.AddChild(textBox);

textBox.CaretIndexChanged += (_, _) =>
{
    UpdateLabelToTextBox(label, textBox);
};

static void UpdateLabelToTextBox(Label label, TextBox textBox)
{
    label.Text = "Text box text: " + textBox.Text + 
        " with caret index " + textBox.CaretIndex;
}

TextWrapping

The TextWrapping property can be used to set whether the TextBox wraps text. By default this value is set to TextWrapping.NoWrap which means the text does not wrap, but instead extends horizontally.

If TextWrapping is set to TextWrapping.Wrap, then text wraps to multiple lines. Note that usually this is combined with a taller text box so that multiple lines display properly.

wrappedTextBox.TextWrapping = TextWrapping.Wrap;
// If you have set up your TextBox in code, you may need to make it taller:
wrappedTextBox.Height = 140;

Extended Character Sets and Keyboards

Characters must be available in the current font to support being written in TextBoxes. If you would like to support more characters, you can explicitly create a font (.fnt) including the desired characters, or change the default character set in Gum.

PreviousSliderNextControl Customization In Code

Last updated 1 month ago

Was this helpful?

The TextBox supports entering characters respecting the current keyboard language settings. This includes typing characters with accents, pasting text, and entering alt codes ( ).

For more information on creating fonts, see the and pages. For more information on specifying the default character set in Gum, see the page.

https://www.alt-codes.net/
Font
Use Custom Font
Interacting with TextBoxes
Key repeat rate adjusted in Windows
TextBox only allowing numbers
TextBox with IsReadOnly set to true responding to mouse click+drag and double-click
Double-click selects all text
Push+drag to select text
Arrow keys + shift to select
CaretIndexChanged is invoked whenever the caret index changes, which updates the Label's text.
TextWrapping.NoWrap causes text to scroll
TextWrapping.Wrap causes text to wrap
TextBox displaying the é character
Project Property Font Ranges