Button
A Button is the control that turns a user's intention into a method call. It raises Click when the user presses it, and the handler runs on the user-interface thread, inside the message loop. Everything else about a button is about when it may be pressed, what it looks like, and which one Enter and Escape press.
A button and its Click
using System;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
internal sealed class Form1 : Form
{
private readonly TextBox _name = new() { Location = new Point(16, 20), Width = 260 };
private readonly Label _greeting = new() { Location = new Point(16, 96), AutoSize = true };
private readonly Button _hello = new()
{
Text = "&Say hello",
Location = new Point(292, 18),
Size = new Size(110, 27),
};
public Form1()
{
Text = "Buttons";
ClientSize = new Size(420, 140);
_hello.Click += OnHello;
_name.TextChanged += (sender, e) => _hello.Enabled = _name.Text.Length > 0;
_hello.Enabled = false;
Controls.Add(_name);
Controls.Add(_hello);
Controls.Add(_greeting);
}
private void OnHello(object? sender, EventArgs e)
{
_greeting.Text = $"Hello, {_name.Text}!";
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run: there is no desktop here. Its behaviour is the documented one, and two lines carry it. _hello.Click += OnHello; subscribes the handler, which gives the button something to do. _hello.Enabled = false; greys the button out, and the TextChanged handler turns it back on as soon as the text box has a character. That is the standard pattern for a form whose submit button must not be pressed with an empty field.
The properties of a button
- Text: what the button says. An ampersand marks an access key (&Say hello answers to Alt+S), and the ampersand is not drawn.
- Enabled: a disabled button is drawn greyed, takes no focus and raises no Click. Use it rather than a check inside the handler when the reason is visible to the user.
- Visible: a hidden button takes no space; the layout closes over it.
- DialogResult: set it to OK, Cancel or another value and the button closes its modal form and returns that value from ShowDialog. On a form shown with Show it does nothing.
- FlatStyle: Standard draws the themed button, Flat a flat one that highlights under the pointer, Popup a flat one that takes a 3D border when pressed. UseVisualStyleBackColor keeps the themed background when BackColor is not set.
- PerformClick(): raises Click in code, as if the user had pressed it. It is what a test or a shortcut calls, and it respects Enabled.
The handler signature
Click is an EventHandler: a method that takes object? sender and EventArgs e and returns void. A method with another signature cannot be subscribed, and the compiler says so:
using System;
using System.Windows.Forms;
internal sealed class Form1 : Form
{
private readonly Button _ok = new() { Text = "OK" };
public Form1()
{
Controls.Add(_ok);
_ok.Click += OnClick;
}
private void OnClick(string text)
{
Console.WriteLine(text);
}
}
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
dotnet build app.csproj
Program.cs(21,9): error CS0123: No overload for 'OnClick' matches delegate 'EventHandler'
The fix is the signature, not a cast: private void OnClick(object? sender, EventArgs e). The sender parameter is the control that raised the event, which is how one handler serves several buttons:
using System;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
internal sealed class Form1 : Form
{
private readonly Label _result = new() { Location = new Point(16, 60), AutoSize = true };
public Form1()
{
Text = "One handler, two buttons";
ClientSize = new Size(300, 110);
var up = new Button { Text = "+1", Location = new Point(16, 16) };
var down = new Button { Text = "-1", Location = new Point(120, 16) };
up.Click += OnStep;
down.Click += OnStep;
Controls.Add(up);
Controls.Add(down);
Controls.Add(_result);
}
private void OnStep(object? sender, EventArgs e)
{
var button = (Button)sender!;
_result.Text = button.Text == "+1" ? "one more" : "one fewer";
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
Reading a control out of sender is allowed and common, and it is worth knowing the alternative: a lambda that closes over the value it needs, up.Click += (sender, e) => Step(1);. The lambda is clearer; the shared handler is what a designer-generated form often has.
The default and the cancel button
A dialog has two buttons that the keyboard reaches without tabbing: AcceptButton is pressed by Enter, CancelButton by Escape. Both are properties of the form, not of the button:
using System;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
var dialog = new Form1();
Console.WriteLine(dialog.ShowDialog());
}
}
internal sealed class Form1 : Form
{
public Form1()
{
Text = "Rename";
ClientSize = new Size(320, 120);
FormBorderStyle = FormBorderStyle.FixedDialog;
MaximizeBox = false;
MinimizeBox = false;
StartPosition = FormStartPosition.CenterParent;
var box = new TextBox { Location = new Point(16, 16), Width = 280 };
var ok = new Button
{
Text = "OK",
Location = new Point(130, 56),
DialogResult = DialogResult.OK,
};
var cancel = new Button
{
Text = "Cancel",
Location = new Point(218, 56),
DialogResult = DialogResult.Cancel,
};
AcceptButton = ok;
CancelButton = cancel;
Controls.Add(box);
Controls.Add(ok);
Controls.Add(cancel);
}
}
The program is built and not run. ShowDialog opens the form as a modal dialog and returns the DialogResult of the button that closed it; Escape and the title bar's close button both give Cancel, because CancelButton and the form's own cancel button are wired that way. That value is how a dialog reports what the user decided, and lesson 042, about a custom dialog, builds on it.
Exercises
- Give the two buttons of the shared handler a Tag instead of reading their text, and explain which is more robust.
- Make the dialog's OK button DialogResult.None and close the form by hand after a check.
- Call PerformClick() on the disabled button and explain why nothing happens.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which event does a button raise when the user presses it?
Answer
Click
Click is the EventHandler every button exposes, and PerformClick raises it in code.
-
Which signature does a Click handler need?
Answer
void Handler(object? sender, EventArgs e)
Click is an EventHandler; another signature fails with CS0123.
-
What does the CS0123 line in this lesson report?
Answer
No overload for 'OnClick' matches delegate 'EventHandler'
The method took a string, and the delegate passes an object and an EventArgs.
-
What does a disabled button do?
Answer
It is drawn greyed, takes no focus and raises no Click
Enabled = false removes the button from the interaction entirely.
-
Which property makes a button close a modal form with a result?
Answer
DialogResult
The value of DialogResult on the button becomes the return value of ShowDialog.
-
What does AcceptButton on a form do?
Answer
Makes Enter press that button
It is the default button of the form; CancelButton does the same for Escape.
-
What does PerformClick() do?
Answer
Raises Click as if the user had pressed the button
It is the programmatic press, and it respects Enabled.
-
How does one handler serve two buttons?
Answer
Read the control out of sender, or close over the value in a lambda
sender is the control that raised the event, which is why the parameter is there.
-
What does the ampersand in a button's Text do?
Answer
Marks the access key, which is not drawn
Alt plus the marked character presses the button, as with a label.
-
Why does the greyed-out button in the first listing come back on?
Answer
The TextChanged handler sets Enabled when the text box is not empty
The form keeps the rule in one place: the button is enabled exactly when the field has text.
Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows.
Article author: Arthur Isaev