0% found this document useful (0 votes)
361 views21 pages

C# Windows Forms Tutorial - Learn C# GUI Programming With Windows Forms

The document provides examples of creating and using different Windows Forms controls in C# such as buttons, tooltips, labels, and quit buttons. It demonstrates how to initialize forms, add controls to forms, set control properties, add event handlers, and close forms. The examples include displaying a simple window, adding tooltips to controls, creating a quit button that closes the application when clicked, and displaying multiline text in a label control.

Uploaded by

Joe Brody
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
361 views21 pages

C# Windows Forms Tutorial - Learn C# GUI Programming With Windows Forms

The document provides examples of creating and using different Windows Forms controls in C# such as buttons, tooltips, labels, and quit buttons. It demonstrates how to initialize forms, add controls to forms, set control properties, add event handlers, and close forms. The examples include displaying a simple window, adding tooltips to controls, creating a quit button that closes the application when clicked, and displaying multiline text in a label control.

Uploaded by

Joe Brody
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

ZetCode

All Spring Boot Python C# Java JavaScript Subscribe

C# Windows Forms tutorial


last modified July 5, 2020

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.

T’s & C’s apply

Windows Forms
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.

Tweet
Like 6 Share

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.

Building Windows Forms applications


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.

Windows Forms simple example


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.

Program.cs
using System;
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;
using System.Windows.Forms;
using System.Drawing;

We use the Windows Forms and Drawing namespaces.

public class MyForm : Form


{
...
}
In 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()
{
InitComponents();
}

As a good programming practice, the form initialization is delegated to the InitComponents()


method.

private void InitComponents()


{
Text = "First application";
ClientSize = new Size(800, 450);
CenterToScreen();
}

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.

Windows Forms tooltips


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.

Program.cs
using System;
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.

Ad

Save €168 on Virgin Media


Sign up now
Virgin Media Ireland

Windows Forms Quit button


Button control represents a Windows button control. It can be clicked by using the mouse, Enter
key, or Spacebar if the button has focus.

Program.cs
using System;
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 += new EventHandler(OnClick);

flowPanel.Controls.Add(button);
Controls.Add(flowPanel);

CenterToScreen();
}

void OnClick(object sender, EventArgs e)


{
Close();
}

[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 += new EventHandler(OnClick);

We plug an event handler to the Click event. When we click on the button, the OnClick() method
is called.

void OnClick(object sender, EventArgs e)


{
Close();
}

The method closes the application with the Close() method.

Windows Forms Label


Label is a simple control for displaying text or images. It does not receive focus.
Program.cs
using System;
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.

Windows Forms CheckBox


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.

Program.cs
using System;
using System.Windows.Forms;
using System.Drawing;

namespace CheckBoxEx
{
class MyForm : Form
{
private FlowLayoutPanel FlowPanel;
private CheckBox cb;

public MyForm()
{
InitUI();
}

private void InitUI()


{
Text = "CheckBox";
ClientSize = new Size(450, 250);

FlowPanel = new FlowLayoutPanel();

var pad = new Padding(20);

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 (cb.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 (cb.Checked)
{
Text = "CheckBox";
}
else
{
Text = "";
}
}

Depending on the value of the Checked property, we toggle the title of the window.

Windows Forms simple menu


A menubar is a collection of menus. A menu groups commands of an application.
Program.cs
using System;
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,
new EventHandler(OnExit));

exitMenuItem.ShortcutKeys = Keys.Control | Keys.X;


fileMenuItem.DropDownItems.Add(exitMenuItem);

ms.Items.Add(fileMenuItem);
MainMenuStrip = ms;
ClientSize = new Size(450, 300);

CenterToScreen();
}

void OnExit(object sender, EventArgs e)


{
Close();
}

[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,


new EventHandler(OnExit));

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.

Windows Forms painting rectangles


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.

Program.cs
using System;
using System.Drawing;
using System.Threading.Tasks;
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 tutorial, we have created simple GUI applications in C# and Windows Forms.

List all C# tutorials.


Home Facebook Twitter Github Subscribe Privacy
© 2007 - 2020 Jan Bodnar admin(at)zetcode.com

You might also like