For the complete documentation index, see llms.txt. This page is also available as Markdown.

Button

Introduction

The Button control providing an event for handling clicks.

Code Example: Adding a Button

The following code adds a button which increments every time it is clicked:

Button button;

void SomeInitializationFunction()
{
    ...
    button = new Button();
    button.AddToRoot();
    button.X = 50;
    button.Y = 50;
    button.Width = 100;
    button.Height = 50;
    button.Text = "Hello MonoGame!";
    int clickCount = 0;
    button.Click += HandleClick
}

void HandleClick(object sender, EventArgs args)
{
    clickCount++;
    button.Text = $"Clicked {clickCount} times";
}

Try on XnaFiddle.NET

Button responding to clicks by incrementing clickCount

Clicking Programmatically

Clicking can be performed programmatically by calling PerformClick. The following example shows how to click a button when the Enter key is pressed. The Click handler updates the button text with the current time:

Try on XnaFiddle.NET

Optionally you can pass the input device to the PerformClick method. The input device is then available in the Click handler through InputEventArgs, which is useful to determine how the button was activated:

Try on XnaFiddle.NET

Animating on Hover

A button changes between its Enabled, Highlighted, Pushed, and Disabled states automatically and instantly. To play a keyframe animation when the button is highlighted (for example, growing or shrinking on hover), subscribe to the visual's RollOn and RollOff events and call PlayAnimation. See Playing Animations on Hover or Highlight for details.

Last updated

Was this helpful?