Win Forms Tutorial
Win Forms Tutorial
Win Forms Tutorial
March 2021
(a) Choose Windows Forms App (WITHOUT .NET Framework in title). Project tem-
plate can be found with filters:
• Language → C#
• Platform → Windows
• Project type → Desktop
1
(b) Choose name and location for your project
2
2. Compile and get familiar with generated files
(a) Compile and run application. Note that one empty window will appear. Close it and
check the generated files.
(b) Investigate file ”Program.cs”. It contains the ”Main” method, the entry point for
your application.
1 static void Main()
2 {
3 Application.SetHighDpiMode(HighDpiMode.SystemAware);
4 Application.EnableVisualStyles();
5 Application.SetCompatibleTextRenderingDefault(false);
6 Application.Run(new Form1());
7 }
The most important line is Application.Run(new Form1()), which starts application
message loop and shows Form1 form.
(c) Open file ”Form1.cs”. Note that instead of code you will see Form Designer. It allows
you to add, remove, edit controls on your forms using graphics interface.
(d) Right-click ”Form1.cs” in solution explorer and click View Code. You will see ”Code-
behind” of the form:
3
1 public partial class Form1 : Form
2 {
3 public Form1()
4 {
5 InitializeComponent();
6 }
7 }
It’s a place where you should write logic for the form. Note, that Form1 class is derived
from the Form class – one of the fundamental classes of Windows Forms. Note also
that Form1 class is marked partial.
(e) Open ”Form1.Designer.cs” – under ”Form1.cs” tree. This file is used by Form
Designer. It’s second part of Form1 class. You should’t change this file, unless you know
what you are doing. All changes to this file will be lost after using Form Designer – so
don’t place your code here!
3. Add controls to the form
(a) Add controls to Form. Open Form Designer. Open Toolbox (View → Toolbox). You
can see there all available controls. Find and place on the Form the following controls:
Label, Textbox, Button.
(b) Show control properties. Right click on Label control and choose Properties. In
properties box, you can adjust controls. Go through the list and make yourself familiar
with available options. Remember that this list may be different for different controls.
(c) Change names of controls. The Name is common for all controls and it’s a name of
control to use in ”Code-Behind”. Name of each control on the form must be unique.
• Set Name of Label to ”nameLabel”
• Set Name of Textbox to ”nameTextBox”
• Set Name of Button to ”goButton”
(a) List of all controls in the window (b) Properties of the button
4
(d) Set other properties:
• Change size of Form to 200x200. Use Size property or mouse in Form Designer
5
(f) Add code-behind. To respond to user’s interaction you must add event handlers to your
controls. To see all available events for a control, select it in the Form Designer, and
click Events button in the properties box.
6
Figure 9: Main form and message box
(i) Add Validation event handler for nameTextBox (Events → Focus → Validating):
7
1 private void nameTextBox_Validating(object sender, CancelEventArgs e)
2 {
3 if (nameTextBox.Text.Length == 0 || nameTextBox.Text.Length > 6)
4 {
5 nameErrorProvider.SetError(nameTextBox,
6 "Name must contain from 1 to 6 characters");
7 e.Cancel = true;
8 return;
9 }
10 nameErrorProvider.SetError(nameTextBox, string.Empty);
11 e.Cancel = false;
12 }
(j) Change your goButton Click method to the following:
1 private void goButton_Click(object sender, EventArgs e)
2 {
3 if (this.ValidateChildren())
4 MessageBox.Show("Welcome " + nameTextBox.Text);
5 }
(k) Run your application. Leave empty textbox and click ”OK”. Note that the message
box doesn’t show up. Instead you can see error icon with error message next to textbox.
Write something correct in textbox and see that icon hides and message box shows up.
(l) Disable AutoValidation. You may find impossible to close window when textbox is
invalid. To correct that set Form1 property AutoValidate to Disable (Properties →
Behavior → AutoValidate).
8
Using Controls – Calendar Manager
1. Create new project, name it ”WinFormsCalendar”
2. Create layout
• Change color of the Split Container. Split container contains 2 panels and a splitter
between them. It allows user to change size of the panels by moving the splitter. However,
splitter’s color is the same as panels, so it is invisible. To change the color, do the
following:
– Set splitContainer Back Color to LightSteelBlue. If you have problem selecting
SplitContainer in the Designer, use menu at the top of properties box.
9
Figure 13: Split container on control list and its properties
• Color of panels also changed. Now select first panel and change its back color to Con-
trolLight, the same for the second panel.
• Run the application. You should see the splitter and be able to change its position.
3. Anchoring controls
• Add two controls to the top panel: MonthCalendar and TextBox. Name them ”mon-
thCalendar” and ”noteTextBox”, respectively
• Set Calendar properties
– Set CalendarDimensions Width to 2 (Appearance → CalendarDimensions)
– Set MaxSelectionCount to 1 (Behavior → MaxSelectionCount)
• Set TextBox properties
– Set Multiline to True (Behavior → Multiline)
• Set controls layout. Place Calendar in the top-left corner of the Panel. Resize the
Textbox to fill the rest of it.
10
Figure 14: Calendar window layout
• Start application. Try resizing window. Notice that the size of the textbox doesn’t
change.
• Go back to the Form Designer. Change noteTextBox Anchor property to Top Bot-
tom Left Right.
• Start Application again and see that resizing works properly.
4. Add collection control
11
• Set following properties
(a) addButton Text to ”Add”
(b) removeButton Text to ”Remove”
(c) removeButton Enabled to False (Behavior → Enabled)
(d) calendarListView View to Details (Appearance → View)
(e) calendarListView FullRowSelect to True (Appearance → FullRowSelect)
(f) calendarListView Anchor to Top Bottom Left Right
• Start application again and see that resizing works properly. Select calendarListView.
In properties box find Columns and click [. . . ] button. You will see List View column
editor. Add 2 columns:
(a) Name: ”dateColumnHeader”; Text: ”Date”; Width: 120
(b) Name: ”noteColumnHeader”; Text: ”Note”; Width: 200
12
Note that to add item to the ListView you must create a ListViewItem object.
Because we have 2 columns in our ListView, the ListViewItem should have 2
values – date and note.
• Run application and try adding some items to our ListView.
13
Figure 18: Removing items from Calendar
14
• Context menu:
– Add ContextMenuStrip control to our form, named ”notifyIconContextMenu”
– Add Load Event Handler to Form1:
1 private void Form1_Load(object sender, EventArgs e)
2 {
3 notifyIconContextMenu.Items.Add("Exit", null, ExitContextMenu_Click);
4 }
– Add Event handler for above menu item:
1 private void ExitContextMenu_Click(object sender, EventArgs e)
2 {
3 Close();
4 }
– Set notifyIcon’s ContextMenuStrip property to notifyIconContextMenu
• Run application and right click on the notify icon.
2. Create layout
• Set Form defaults
– Set Size of the form to 800 x 500
– Set StartPosition to Center Screen
– Set Locked to True
• Table Layout Panel:
– Add a Table Layout Panel to the form.
– Rename it to ”galleryLayoutPanel”.
– Set Anchor to Top, Bottom, Left, Right
– Change second column Width to 25%
15
Figure 21: TableLayoutPanel columns and rows settings
• Run application and notice that nothing is visible. Table Layout Panel is just a container.
We need to fill it with controls.
3. Add Buttons
• Add Choose Image button to Top Right Panel
– Change its Name to ”imageButton”
– Change its Text to ”Choose Image”
– Change its Dock to Fill
• Add Choose Color button to Bottom Right Panel
– Change its Name to ”colorButton”
– Change its Text to ”Choose Color”
– Change its Dock to Fill
16
Figure 22: Application layout
17
Figure 23: ColorButton logic
18
Figure 24: ImageButton logic
19
1 drawArea = new Bitmap(Canvas.Size.Width, Canvas.Size.Height);
2 Canvas.Image = drawArea;
3 using(Graphics g = Graphics.FromImage(drawArea))
4 {
5 g.Clear(Color.LightBlue);
6 }
– Alternatively, you can replace lines 3-6 with:
1 Graphics g = Graphics.FromImage(drawArea);
2 g.Clear(Color.LightBlue);
3 g.Dispose();
– Keep in mind that all GDI+ objects must be disposed after usage to prevent memory
leaks.
• Run the application, it should be filled with a light blue color.
20
• Add a constant field in the Form1 class:
1 private const int RADIUS = 10;
• Add following code to the event:
1 if(e.Button == MouseButtons.Left)
2 {
3 using (Graphics g = Graphics.FromImage(drawArea))
4 {
5 g.FillEllipse(Brushes.White, e.X - RADIUS, e.Y - RADIUS, RADIUS * 2, RADIUS * 2);
6 }
7 Canvas.Refresh();
8 }
• Run the application and press LMB in the window. Keep in mind that Canvas.Refresh()
is necessary in order to be able to see changes on the bitmap.
21
1 if(e.Button == MouseButtons.Left)
2 {
3 using (Graphics g = Graphics.FromImage(drawArea))
4 {
5 g.FillEllipse(Brushes.White, e.X - RADIUS, e.Y - RADIUS, RADIUS * 2, RADIUS * 2);
6 g.DrawEllipse(pen, e.X - RADIUS, e.Y - RADIUS, RADIUS * 2, RADIUS * 2);
7 }
8 Canvas.Refresh();
9 }
• Run the application and press LMB in the window. Circles should now have an outline.
22
4 {
5 g.FillEllipse(Brushes.White, e.X - RADIUS, e.Y - RADIUS, RADIUS * 2, RADIUS * 2);
6 g.DrawEllipse(dashedPen, e.X - RADIUS, e.Y - RADIUS, RADIUS * 2, RADIUS * 2);
7 }
8 Canvas.Refresh();
9 }
• Run the application and press some LMB and RMB in the window. LMB draws a circle
with a normal outline, RMB draws a circle with a dashed outline.
23