githubEdit

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.NETarrow-up-right

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.NETarrow-up-right

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.NETarrow-up-right

Last updated

Was this helpful?