C# Windows Forms tutorial teaches the basics of GUI programming with C# & Windows Forms. In our tutorial, we will build our applications manually; we will not use Form designers.
Windows Forms, sometimes abbreviated as Winforms, is a graphical user interface application programming interface (API) included as a part of Microsoft's .NET Framework.
Windows Forms allows to create graphically rich applications that are easy to deploy and update. The applications are more secure than traditional Windows-based applications.
In December 2018, Microsoft announced releasing Windows Forms as open source project on GitHub. It is released under the MIT License. With this release, Windows Forms has become available on the .NET Core framework. Windows Forms is available on Windows only.
We will be using .NET Core to create Windows Forms applications.
$ dotnet new winforms -o MyApp
A new template for the Windows Forms application is created with the dotnet new winforms command.
$ dotnet run
The application is run with the dotnet run command.
In the first example, we display a simple window on the screen.
$ dotnet new winforms -o First
We create the template of the Windows Forms application. The command also generates Form1.Designer.cs and Form1.cs files. We will not use them and they can be safely deleted.
using System.Windows.Forms; using System.Drawing; namespace First < public class MyForm : Form < public MyForm() < InitComponents(); >private void InitComponents() < Text = "First application"; ClientSize = new Size(800, 450); CenterToScreen(); >[STAThread] static void Main() < Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.Run(new MyForm()); >> >
The example displays a main window on the screen. The window is centered.
using System.Windows.Forms; using System.Drawing;
We use the Windows Forms and Drawing namespaces.
public class MyForm : FormIn Windows Forms, any window or a dialog is a Form. This control is a basic container whose purpose is to display other child controls. The MyForm inherits from a form. This way it becomes a form itself.
public MyForm()As a good programming practice, the form initialization is delegated to the InitComponents method.
private void InitComponents()Text and Size are properties of a form. Changing these properties, we modify our form control. The first line displays text "First application" in the titlebar of the form control. The second line sets the size of the client area of the form. The CenterToScreen method centers the form on the screen.
[STAThread] static void Main()The Main method is an entry point to the application. Windows Forms applications must declare the [STAThread] attribute; otherwise, the controls might not work correctly. This tells to use single-threaded apartment model instead of multi-threaded.
Application.SetHighDpiMode(HighDpiMode.SystemAware);
With the SetHighDpiMode method, we ensure that our application looks good on any display resolution.
Application.EnableVisualStyles();
The EnableVisualStyles method enables visual styles. The application will use the built-in Windows theming to style controls instead of the classic Windows look and feel.
Application.Run(new MyForm());
The Run method starts the application. It begins running a standard application message loop on the current thread, and makes the specified form visible.
A tooltip is a small rectangular pop-up window that displays a brief description of a control's purpose when the user rests the pointer on the control.
using System.Drawing; using System.Windows.Forms; namespace Tooltips < public class MyForm : Form < private FlowLayoutPanel flowPanel; public MyForm() < InitComponents(); >private void InitComponents() < Text = "Tooltips"; ClientSize = new Size(800, 450); flowPanel = new FlowLayoutPanel(); var ftip = new ToolTip(); ftip.SetToolTip(flowPanel, "This is a FlowLayoutPanel"); flowPanel.Dock = DockStyle.Fill; flowPanel.BorderStyle = BorderStyle.FixedSingle; var button = new Button(); button.Text = "Button"; button.AutoSize = true; var btip = new ToolTip(); btip.SetToolTip(button, "This is a Button Control"); var button2 = new Button(); button2.Text = "Button 2"; button2.AutoSize = true; flowPanel.Controls.Add(button); flowPanel.Controls.Add(button2); Controls.Add(flowPanel); CenterToScreen(); >[STAThread] static void Main() < Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.Run(new MyForm()); >> >
The code example creates a tooltip for two controls: one Button control and the Form control.
flowPanel = new FlowLayoutPanel();
We place two buttons on the FlowLayoutPanel . It dynamically lays out its contents horizontally or vertically. (The default dimension is vertical.)
var ftip = new ToolTip(); ftip.SetToolTip(flowPanel, "This is a FlowLayoutPanel");
We create a new tooltip. With the SetToolTip , we assign the tooltip to the FlowLayoutPanel control.
flowPanel.Dock = DockStyle.Fill;
The FlowLayoutPanel fills the entire area of the form control.
var button = new Button(); button.Text = "Button"; button.AutoSize = true;
A new Button control is created. We set its text with the Text property and size it automatically to fit the text size.
var btip = new ToolTip(); btip.SetToolTip(button, "This is a Button Control");
A tooltip is added to the first Button control.
flowPanel.Controls.Add(button); flowPanel.Controls.Add(button2); Controls.Add(flowPanel);
The buttons are added to the flow panel and the flow panel is added to the form.
Button control represents a Windows button control. It can be clicked by using the mouse, Enter key, or Spacebar if the button has focus.
using System.Windows.Forms; using System.Drawing; namespace QuitButton < class MyForm : Form < private FlowLayoutPanel flowPanel; public MyForm() < InitComponents(); >private void InitComponents() < Text = "Quit button"; ClientSize = new Size(800, 450); flowPanel = new FlowLayoutPanel(); flowPanel.Dock = DockStyle.Fill; flowPanel.BorderStyle = BorderStyle.FixedSingle; var button = new Button(); button.Margin = new Padding(10, 10, 0, 0); button.Text = "Quit"; button.AutoSize = true; button.Click += (_, _) =>Close(); flowPanel.Controls.Add(button); Controls.Add(flowPanel); CenterToScreen(); > [STAThread] static void Main() < Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.Run(new MyForm()); >> >
The example creates a Quit button control; the application terminates when we click on the button.
var button = new Button(); button.Margin = new Padding(10, 10, 0, 0);
The button has some margin around its borders. We add some space to the left and above the button control.
button.Click += (_, _) => Close();
We plug an event handler to the Click event. When we click on the button, the application is closed with the Close method. Since we do not work with the sender object and event arguments, we use discards.
Label is a simple control for displaying text or images. It does not receive focus.
using System.Drawing; using System.Windows.Forms; namespace LabelEx < public class MyForm : Form < public MyForm() < InitUI(); >private void InitUI() < string text = @" Spending my time Watching the days go by Feeling so small, I stare at the wall Hoping that you think of me too I'm spending my time I try to call but I don't know what to tell you I leave a kiss on your answering machine Oh, help me please, is there someone who can make me Wake up from this dream? "; var font = new Font("Serif", 10); var lyrics = new Label(); lyrics.Parent = this; lyrics.Text = text; lyrics.Font = font; lyrics.Location = new Point(10, 10); lyrics.AutoSize = true; CenterToScreen(); Text = "Label"; AutoSize = true; CenterToScreen(); >[STAThread] static void Main() < Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.Run(new MyForm()); >> >
The example displays lyrics using the Label control.
var font = new Font("Serif", 10);
We use this font to display the text.
var lyrics = new Label(); lyrics.Parent = this; lyrics.Text = text; lyrics.Font = font; lyrics.Location = new Point(10, 10); lyrics.AutoSize = true;
The label control is created. It is located at the x=10, y=10 coordinate on the form.
Text = "Label"; AutoSize = true; CenterToScreen();
The main window is automatically sized to fit the lyrics.
CheckBox is a control that has two states: on and off. It is a box with a label or an image. If the CheckBox is checked, it is represented by a tick in a box.
using System.Windows.Forms; using System.Drawing; namespace CheckBoxEx < class MyForm : Form < private FlowLayoutPanel FlowPanel; public MyForm() < InitUI(); >private void InitUI() < Text = "CheckBox"; ClientSize = new Size(450, 250); FlowPanel = new FlowLayoutPanel(); var pad = new Padding(20); var cb = new CheckBox(); cb.Margin = pad; cb.Parent = this; cb.Text = "Show Title"; cb.AutoSize = true; cb.Checked = true; cb.CheckedChanged += new EventHandler(OnChanged); FlowPanel.Controls.Add(cb); Controls.Add(FlowPanel); CenterToScreen(); >void OnChanged(object sender, EventArgs e) < if (((CheckBox )sender).Checked) < Text = "CheckBox"; >else < Text = ""; >> [STAThread] static void Main() < Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.Run(new MyForm()); >> >
The code example shows or hides the title of the window depending on its state.
var pad = new Padding(20); cb = new CheckBox(); cb.Margin = pad; cb.Parent = this; cb.Text = "Show Title"; cb.AutoSize = true; cb.Checked = true;
When the application starts, we show the title. And we set the CheckBox control to checked state.
cb.CheckedChanged += new EventHandler(OnChanged);
When we click on the CheckBox control, the CheckedChanged event is triggered.
void OnChanged(object sender, EventArgs e) < if (((CheckBox )sender).Checked) < Text = "CheckBox"; >else < Text = ""; >>
Depending on the value of the Checked property, we toggle the title of the window.
A menubar is a collection of menus. A menu groups commands of an application.
using System.Drawing; using System.Windows.Forms; namespace MenuEx < class MyForm : Form < public MyForm() < Text = "Simple menu"; var ms = new MenuStrip(); ms.Parent = this; var fileMenuItem = new ToolStripMenuItem("&File"); var exitMenuItem = new ToolStripMenuItem("&Exit", null, (_, _) =>Close()); exitMenuItem.ShortcutKeys = Keys.Control | Keys.X; fileMenuItem.DropDownItems.Add(exitMenuItem); ms.Items.Add(fileMenuItem); MainMenuStrip = ms; ClientSize = new Size(450, 300); CenterToScreen(); > [STAThread] static void Main() < Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.Run(new MyForm()); >> >
In our example, we have a menubar and one menu. Inside a menu there is one menu item. If we select the menu item, application is closed.
The application can be closed also by using the Ctrl + X shorcut or by pressing Alt , F , E keys.
var ms = new MenuStrip();
MenuStrip creates a menu system for our form. We add ToolStripMenuItem objects to the MenuStrip that represent the individual menu commands in the menu structure. Each ToolStripMenuItem can be a command for your application or a parent menu for other submenu items.
var fileMenuItem = new ToolStripMenuItem("&File");
Here we create a menu with the ToolStripMenuItem .
var exitMenuItem = new ToolStripMenuItem("&Exit", null, (_, _) => Close());
This line creates the exit menu item.
exitMenuItem.ShortcutKeys = Keys.Control | Keys.X;
We provide a shortcut for the exit menu item.
fileMenuItem.DropDownItems.Add(exitMenuItem);
The exit menu item is added to the drop down items of the menu object.
ms.Items.Add(fileMenuItem);
Here we add the menu object into the menu strip.
MainMenuStrip = ms;
The MenuStrip is plugged into the form. In other words, the menubar is added to the main window of the application.
Painting is done with the painting API provided by the Windows Forms. The painting is done within a method, that we plug into the Paint event.
using System.Drawing; using System.Windows.Forms; namespace RectanglesEx < class Program : Form < public Program() < InitUI(); >private void InitUI() < Text = "Rectangles"; Paint += new PaintEventHandler(OnPaint); ClientSize = new Size(550, 450); CenterToScreen(); >void OnPaint(object sender, PaintEventArgs e) < Graphics g = e.Graphics; g.FillRectangle(Brushes.Sienna, 10, 15, 90, 60); g.FillRectangle(Brushes.Green, 130, 15, 90, 60); g.FillRectangle(Brushes.Maroon, 250, 15, 90, 60); g.FillRectangle(Brushes.Chocolate, 10, 105, 90, 60); g.FillRectangle(Brushes.Gray, 130, 105, 90, 60); g.FillRectangle(Brushes.Coral, 250, 105, 90, 60); g.FillRectangle(Brushes.Brown, 10, 195, 90, 60); g.FillRectangle(Brushes.Teal, 130, 195, 90, 60); g.FillRectangle(Brushes.Goldenrod, 250, 195, 90, 60); >[STAThread] static void Main() < Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.Run(new Program()); >> >
We draw nine rectangles with nine different colours.
Paint += new PaintEventHandler(OnPaint);
Paint events are delivered to the OnPaint method.
void OnPaint(object sender, PaintEventArgs e)This is the signature of the OnPaint method.
Graphics g = e.Graphics;
In order to paint on the form, we must get the Graphics object. Painting on a form is actually calling various methods of the Graphics object.
g.FillRectangle(Brushes.Sienna, 10, 15, 90, 60);
The FillRectagle method fills a specified rectangle with a brush. A brush can be a colour or a pattern. There are some predefined colours available. We can get them from the Brushes enumeration. The last four values are the x, y values of the topleft point and the width and height of the rectangle.
In this article we have created simple GUI applications in C# and Windows Forms.
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.