Button
Introduction
The Button control providing an event for handling clicks.
Click, not Push, is the primary event for reacting to button activation. Its timing depends on the input device:
Mouse or touch -
Clickfires on release, after a matching push over the same button. The cursor can leave and return before releasing; see Click for details.Keyboard or gamepad -
Clickfires immediately when the activation key or button is pressed, with no release-based confirmation.
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";
}
Button Height
A button whose HeightUnits is RelativeToChildren grows with a label that wraps onto more lines, and with an empty Text it shrinks to its Height (the padding around the label). Set an explicit Height and HeightUnits of Absolute on an icon-only button.
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:
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:
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?

