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:
...
var button = new Button();
Root.Children.Add(button.Visual);
button.X = 0;
button.Y = 0;
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";
}

Clicking Programatically
Clicking can be performed programatically by calling PerformClick. The following example shows how to click a button when the Enter key is pressed:
var keyboard = FormsUtilities.Keyboard;
if(keyboard.KeyPushed(Microsoft.Xna.Framework.Input.Keys.Enter))
{
button.PerformClick();
}
Optionally you can pass the input device to the PerformClick method:
button.PerformClick(keyboard);
Last updated
Was this helpful?