C#Unit-4 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

Module 4 - Graphical User Interface with Windows Forms and WPF

Windows Forms:
Introduction to Windows Forms:
 Windows Forms is a Graphical User Interface(GUI) class library which is bundled in
.Net Framework.
 Its main purpose is to provide an easier interface to develop the applications for desktop,
tablet, PCs.
 It is also termed as the WinForms.
 The applications which are developed by using Windows Forms or WinForms are
known as the Windows Forms Applications that runs on the desktop computer.
 WinForms can be used only to develop the Windows Forms Applications not web
applications.
 WinForms applications can contain the different type of controls like labels, list boxes,
tooltip etc.

The Windows Forms framework provides a rich set of controls that developers can use to
build applications with. These controls are designed to provide a consistent and familiar
user interface for Windows users. Developers can customize the appearance and behaviour
of these controls by setting various properties and handling events.

To create a Windows Forms application in C#, you can use Microsoft Visual Studio, which is
an integrated development environment (IDE) that provides a visual designer to create and
layout the user interface elements. The visual designer is a drag-and-drop interface for
building your UI, and you can easily configure each control’s properties through a user-
friendly interface.

In addition to the visual designer, Visual Studio also provides a code editor that enables
developers to write the C# code for the application’s logic. Developers can handle events
and perform tasks such as data validation, data manipulation, and business logic
implementation.

Windows Forms applications are versatile and can be used to create various types of
applications such as data entry, management, and reporting applications, as well as games
and multimedia applications.

Overall, Windows Forms applications provide an easy-to-use and familiar graphical user
interface for Windows users, making it an ideal choice for building desktop applications that
require a high degree of interactivity and user engagement.
Control Properties and Layout
Controls derive from class Control (namespace System.Windows.Forms)

Lists some of class Control's properties and methods. The properties shown here can be set
for many controls. For example, the Text property specifies the text that appears on a
control. The location of this text varies depending on the control. In a Windows Form, the
text appears in the title bar, but the text of a Button appears on its face.
Class Control properties
and methods Description
Common Properties
BackColor The control's background color.
BackgroundImage The control's background image.
Enabled Specifies whether the control is enabled (i.e., if the user can interact
with it). Typically, portions of a disabled control appear "grayed
out" as a visual indication to the user that the control is disabled.
Focused Indicates whether the control has the focus.
Font The Font used to display the control's text.
ForeColor The control's foreground color. This usually determines the color of
the text in the Text property.
TabIndex The tab order of the control. When the Tab key is pressed, the focus
transfers between controls based on the tab order. You can set this
order.
TabStop If true, then a user can give focus to this control via the Tab key.
Text The text associated with the control. The location and appearance of
the text vary depending on the type of control.
Visible Indicates whether the control is visible.
Common Methods
Focus Acquires the focus.
Hide Hides the control (sets the Visible property to false).
Show Shows the control (sets the Visible property to true).

Control Layout Properties:

Control layout properties Description


Anchor Causes a control to remain at a fixed distance from the
side(s) of the container even when the container is
resized.
Dock Allows a control to span one side of its container or to
fill the entire container.
Padding Sets the space between a container's edges and docked
controls. The default is 0, causing the control to appear
flush with the containe's sides.
Control layout properties Description
Location Specifies the location (as a set of coordinates) of the
upper-left corner of the control, in relation to its
container.
Size Specifies the size of the control in pixels as
a Size object, which has properties Width and Height.
MinimumSize, MaximumSizeIndicates the minimum and maximum size of
a Control, respectively.

Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New ->
Project -> WindowsFormApp

Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are
allowed to place a Label control anywhere on the windows form according to your need.

Step 3: After drag and drop you will go to the properties of the Label control to set the
properties of the Label according to your need.
Labels in C#
 Labels are one of the most frequently used C# control.
 We can use the Label control to display text in a set location on the page.
 Label controls can also be used to add descriptive text to a Form to provide the user with
helpful information.
 The Label class is defined in the System.Windows.Forms namespace.

Add a Label control to the form - Click Label in the Toolbox and drag it over the forms
Designer and drop it in the desired location.

If you want to change the display text of the Label, you have to set a new text to the Text
property of Label.

label1.Text = "This is my first Label";


Example Program to Describe a label.

using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1{
public partial class Form1 : Form{
public Form1(){
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e){
label1.Text = "VCET Puttur.";
label1.BorderStyle = BorderStyle.FixedSingle;
label1.TextAlign = ContentAlignment.MiddleCenter;
}
}
}

Properties of Label control

Property Description

BackColor It is used to set background color of the label.

BorderColor It is used to set border color of the label.

BorderWidth It is used to set width of border of the label.

Font It is used to set font for the label text.

ForeColor It is used to set color of the label text.

Text It is used to set text to be shown for the label.

ToolTip It displays the text when mouse is over the label.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

2. Text Boxes in C#
In Windows forms, TextBox plays an important role.
With the help of TextBox, the user can enter data in the application,

it can be of a single line or of multiple lines.

The TextBox is a class and it is defined under System.Windows.Forms namespace.

In C#, you can create a TextBox in two different ways:

1. Design-Time: It is the simplest way to create a TextBox as shown in the following steps:

Step 1: Create a windows form. As shown in the below image: Visual Studio -> File -> New -
> Project -> WindowsFormApp

Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You
can place TextBox anywhere on the windows form according to your need.

Step 3: After drag and drop you will go to the properties of the TextBox control to modify
the TextBox design according to your requirement.
2. Run-Time:
It is a little bit trickier than the above method. In this method, you can create your own
textbox using the TextBox class.

Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.
// Creating textbox
TextBox Mytextbox = new TextBox();
Step 2 : After creating TextBox, set the properties of the TextBox provided by the TextBox
class.

// Set location of the textbox


Mytextbox.Location = new Point(187, 51);

// Set background color of the textbox


Mytextbox.BackColor = Color.LightGray;

// Set the foreground color of the textbox


Mytextbox.ForeColor = Color.DarkOliveGreen;

// Set the size of the textbox


Mytextbox.AutoSize = true;

// Set the name of the textbox


Mytextbox.Name = "text_box1";

Property Description

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.


BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

MaxLength It is used to set maximum number of characters that can be


entered.

Readonly It is used to make control readonly.

Step 3 : And last add this textbox control to form using Add() method.
// Add this textbox to form
this.Controls.Add(Mytextbox);

Buttons:
 A Button is an essential part of an application, or software, or webpage.
 It allows the user to interact with the application or software.
 It is typically represented by a clickable button on the screen that performs an action
when clicked by the user.
 For example, if a user wants to exit from the current application so, he/she click the exit
button which closes the application.
 It can be used to perform many actions like to submit, upload, download, etc. according
to the requirement of your program.
 It can be available with different shape, size, color, etc. and you can reuse them in
different applications. In .NET Framework,
 Button class is used to represent windows button control and it is inherited from
ButtonBase class. It is defined under System.Windows.Forms namespace.

In C# you can create a button on the windows form by using two different ways:
1. Design-Time:
It is the easiest method to create a button. Use the below steps:

Step 1: Create a windows form as shown in the below image:


Visual Studio -> File -> New -> Project -> WindowsFormApp

Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are
allowed to place a Button control anywhere on the windows form according to your need.

Step 3: After drag and drop you will go to the properties of the Button control to set the
properties of the Button.

2. Run-Time:
It is a little bit trickier than the above method. In this method, you can create your own
Button using the Button class.
Step 1: Create a button using the Button() constructor is provided by the Button class.
// Creating Button using Button class
Button MyButton = new Button();

Step 2: After creating Button, set the properties of the Button provided by the Button class.
// Set the location of the button
Mybutton.Location = new Point(225, 198);

// Set text inside the button


Mybutton.Text = "Submit";

// Set the AutoSize property of the button


Mybutton.AutoSize = true;

// Set the background color of the button


Mybutton.BackColor = Color.LightBlue;

// Set the padding of the button


Mybutton.Padding = new Padding(6);

// Set font of the text present in the button


Mybutton.Font = new Font("French Script MT", 18);

Step 3: And last add this button control to form using Add() method.
// Add this Button to form
this.Controls.Add(Mybutton);

Property Description

AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.


Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

Group Boxes:
 A GroupBox control is a container control that is used to place Windows Forms child
controls in a group.
 The purpose of a GroupBox is to define user interfaces where we can categorize related
controls in a group.
 In Windows form, GroupBox is a container which contains multiple controls on it and
the controls are related to each other.
 Or in other words, GroupBox is a frame display around a group of controls with a
suitable optional title.
 Or a GroupBox is used to categorize the related controls in a group.
 The GroupBox class is used to represent the windows group box and also provide
different types of properties, methods, and events.
 It is defined under System.Windows.Forms namespace.
 The main use of a group box is to hold a logical group of RadioButton controls.

In C# you can create a GroupBox in the windows form by using two different ways:

1. Design-Time:
It is the easiest way to create a GroupBox as shown in the following steps:

Step 1: Create a windows form as shown in the below image:

Visual Studio -> File -> New -> Project -> WindowsFormApp

Step 2: Next, drag and drop the GroupBox from the toolbox on the form.
Step 3: After drag and drop you will go to the properties of the GroupBox to modify
GroupBox according to your requirements.

Output:
2. Run-Time:
It is a little bit trickier than the above method. In this method, you can create a GroupBox
programmatically with the help of syntax provided by the GroupBox class. The following
steps show how to set the create GroupBox dynamically:

Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox
class.

// Creating a GroupBox

GroupBox box = new GroupBox();

Step 2: After creating GroupBox, set the property of the GroupBox provided by the
GroupBox class.

// Setting the location of the GroupBox

box.Location = new Point(179, 145);

// Setting the size of the GroupBox

box.Size = new Size(329, 94);

// Setting text the GroupBox

box.Text = "Select Gender";

// Setting the name of the GroupBox

box.Name = "MyGroupbox";

Step 3: And last add this GroupBox control to the form and also add other controls on the
GroupBox using the following statements:

// Adding groupbox in the form

this.Controls.Add(box);

Group Box Properties:


Property Description
AutoSize This property is used to get or set a value that indicates whether the control resizes based on its
contents.
AutoSizeMode This property indicates how the GroupBox behaves when its AutoSize property is enabled.
BackColor This property is used to get or set the background color for the control.
BorderStyle This property indicates the border style for the control.
DisplayRectangle This property is used to get a rectangle that represents the dimensions of the GroupBox.
Font This property is used to get or set the font of the text displayed by the control.
ForeColor This property is used to get or set the foreground color of the control.
Height This property is used to get or set the height of the control.
Location This property is used to get or set the coordinates of the upper-left corner of the GroupBox
control relative to the upper-left corner of its form.
Name This property is used to get or set the name of the control.
TabStop This property is used to get or set a value that shows whether the user can press the TAB key to
provide the focus to the GroupBox.
Size This property is used to get or set the height and width of the control.
Visible This property is used to get or set a value indicating whether the control and all its child controls
are displayed.
Width This property is used to get or set the width of the control.

Flow Control Panel

 In Windows Forms, FlowLayoutPanel control is used to arrange its child controls in a


horizontal or vertical flow direction.
 Or in other words, FlowLayoutPanel is a container which is used to organize different or
same types of controls in it either horizontally or vertically.
 The FlowLayoutPanel class is used to represent windows flow layout panel and also
provide different types of properties, methods, and events.
 It is defined under System.Windows.Forms namespace.
 In C#, you can create a FlowLayoutPanel in the windows form by using two different
ways:

Types of Creating
1. Design Phase:
Output:

2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a
FlowLayoutPanel programmatically with the help of syntax provided by the
FlowLayoutPanel class. The following steps show how to set the create FlowLayoutPanel
dynamically:

Step 1: Create a FlowLayoutPanel using the FlowLayoutPanel() constructor is provided by


the FlowLayoutPanel class.

// Creating a FlowLayoutPanel

FlowLayoutPanel fl = new FlowLayoutPanel();

Step 2: After creating a FlowLayoutPanel, set the property of the FlowLayoutPanel provided
by the FlowLayoutPanel class.

// Setting the location of the FlowLayoutPanel

fl.Location = new Point(380, 124);

// Setting the size of the FlowLayoutPanel

fl.Size = new Size(216, 57);

// Setting the name of the FlowLayoutPanel

fl.Name = "Mycontainer";

// Setting the font of the FlowLayoutPanel

fl.Font = new Font("Calibri", 12);

// Setting the flow direction of the FlowLayoutPanel


fl.FlowDirection = FlowDirection.RightToLeft;

// Setting the border style of the FlowLayoutPanel

fl.BorderStyle = BorderStyle.Fixed3D;

// Setting the foreground color of the FlowLayoutPanel

fl.ForeColor = Color.BlueViolet;

// Setting the visibility of the FlowLayoutPanel

fl.Visible = true;

Step 3: And last add this FlowLayoutPanel control to the form and also add other controls
on the FlowLayoutPanel using the following statements:

// Adding a FlowLayoutPanel

// control to the form

this.Controls.Add(fl);

and

// Adding child controls

// to the FlowLayoutPanel

fl.Controls.Add(f1);

Constructor Description
FlowLayoutPanel() This Constructors is used to initialize a new instance of the
FlowLayoutPanel class.

Property Description
AutoScroll This property is used to get or set a value indicating whether the
container enables the user to scroll to any controls placed outside of its
visible boundaries.
AutoSize This property is used to get or set a value that indicates whether the
control resizes based on its contents.
AutoSizeMode This property indicates the automatic sizing behavior of the control.
BackColor This property is used to get or set the background color for the control.
BorderStyle This property indicates the border style for the control.
FlowDirectionThis property is used to get or set a value indicating the flow direction
of the FlowLayoutPanel control.
Font This property is used to get or set the font of the text displayed by the
control.
ForeColor This property is used to get or set the foreground color of the control.
Height This property is used to get or set the height of the control.
Location This property is used to get or set the coordinates of the upper-left
corner of the FlowLayoutPanel control relative to the upper-left corner
of its form.
Name This property is used to get or set the name of the control.
Padding This property is used to get or set padding within the control.
Size This property is used to get or set the height and width of the control.
Visible This property is used to get or set a value indicating whether the control
and all its child controls are displayed.
Width This property is used to get or set the width of the control.
WrapContents This property is used to get or set a value indicating whether the
FlowLayoutPanel control should wrap its contents or let the contents be
clipped.

Radio Button Control


In Windows Forms, RadioButton control is used to select a single option among the group of
the options.
For example, select your gender from the given list, so you will choose only one option
among three options like Male or Female or Transgender.
In C#, RadioButton is a class and it is defined under System.Windows.Forms namespace. In
RadioButton, you are allowed to display text, image, or both and when you select one radio
button in a group other radio buttons automatically clear.
You can create RadioButton in two different ways:
1. Design-Time:
Output:

Run-Time: It is a little bit trickier than the above method. In this method, you can create a
RadioButton programmatically with the help of the RadioButton class. The following steps
show how to create a RadioButton dynamically:
Step 1: Create a radio button using the RadioButton() constructor is provided by the
RadioButton class.
// Creating radio button
RadioButton r1 = new RadioButton();
Step 2: After creating RadioButton, set the properties of the RadioButton provided by the
RadioButton class.
// Set the AutoSize property
r1.AutoSize = true;

// Add text in RadioButton


r1.Text = "Intern";

// Set the location of the RadioButton


r1.Location = new Point(286, 40);

// Set Font property


r1.Font = new Font("Berlin Sans FB", 12);
Step 3: And last add this RadioButton control to the form using Add() method.
// Add this radio button to the form
this.Controls.Add(r1);

Properties of RadioButtons.
Property Description

This property is used to set a value determining the


Appearance appearance of the RadioButton.

This property is used to set a value indicating whether the


Checked value and the appearance of the RadioButton control
AutoCheck automatically change when the RadioButton control is clicked.

This property is used to set a value that indicates whether the


AutoSize RadioButton control resizes based on its contents.

This property is used to set the background color of the


BackColor RadioButton control.

This property is used to set the location of the check box


CheckAlign portion of the RadioButton.

This property is used to set a value indicating whether the


Checked RadioButton control is checked.

This property is used to set the font of the text displayed by the
Font RadioButton control.
This property is used to set the foreground color of the
ForeColor RadioButton control.

This property is used to sets the coordinates of the upper-left


corner of the RadioButton control relative to the upper-left
Location corner of its form.

This property is used to sets the name of the RadioButton


Name control.

This property is used to sets padding within the RadioButton


Padding control.

This property is used to set the text associated with this


Text RadioButton control.

This property is used to set the alignment of the text on the


TextAlign RadioButton control.

This property is used to set a value indicating whether the


Visible RadioButton control and all its child controls are displayed.

Important Events
Event Description

Click This event occurs when the RadioButton control is clicked.

This event occurs when the value of the Checked property


CheckedChanged changes.

This event occurs when the Appearance property value


AppearanceChanged changes.

This event occurs when the user double-clicks the


DoubleClick RadioButton control.

This event occurs when the input focus leaves the


Leave RadioButton control.

This event occurs when the RadioButton control is clicked by


MouseClick the mouse.
This event occurs when the user double-clicks the
MouseDoubleClick RadioButton control with the mouse.

This event occurs when the mouse pointer rests on the


MouseHover RadioButton control.

This event occurs when the mouse pointer leaves the


MouseLeave RadioButton control.

Checkboxes:
 The CheckBox control is the part of windows form which is used to take input from the
user. Or in other words,
 CheckBox control allows us to select single or multiple elements from the given list or it
can provide us options like yes or no, true or false, etc.
 It can be displayed as an image or text or both. The CheckBox is a class and defined
under System.Windows.Forms namespace.
 In Windows form, you can create CheckBox in two different ways:

Design Time

2. Run Time:

2. Run-Time: It is a little bit trickier than the above method. In this method, you can create
your own checkbox programmatically using the CheckBox class.

Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class.

// Creating checkbox

CheckBox Mycheckbox = new CheckBox();

Step 2: After creating CheckBox, set the properties of the CheckBox provided by the
CheckBox class.

// Set height of the checkbox

Mycheckbox.Height = 50;
// Set width of the checkbox

Mycheckbox.Width = 100;

// Set location of the checkbox

Mycheckbox.Location = new Point(229, 136);

// Set text in the checkbox

Mycheckbox.Text = "Married";

// Set font of the checkbox

Mycheckbox.Font = new Font("Bradley Hand ITC", 12);

Step 3: And last add this checkbox control to form using Add() method.

// Add this checkbox to form

this.Controls.Add(Mycheckbox);

Important Properties of CheckBox

Property Description

This property is used to gets or sets the value that


Appearance
indicates the appearance of a CheckBox control.

This property is used to set a value which shows


whether the Checked or CheckState values and the
AutoCheck
CheckBox appearance are automatically changed when
you click the CheckBox.

This property is used to get or set a value which


determine whether the ellipsis character (…) appears at
AutoEllipsis
the right edge of the control, denoting that the control
text extends beyond the specified length of the control.

This property is used to get or set a value that


AutoSize determines whether the control resizes based on its
contents.
Property Description

This property is used to get or set the background color


BackColor
of the control.

This property is used to get or set the background image


BackgroundImage
displayed in the control.

This property is used to get or set the state of the


CheckState
CheckBox.

This property is used to get or set the horizontal and


CheckAlign vertical alignment of the check mark on a CheckBox
control.

This property is used to get or set a value which


Checked determine whether the CheckBox is in the checked state.

This property is used to get the list of event handlers that


Events
are attached to this Component.

This property is used to get or set the font of the text


Font
displayed by the control.

This property is used to get or set the foreground color


ForeColor
of the control.

This property is used to get or set the image that is


Image
displayed on a checkbox control.

This property is used to get or set the coordinates of the


Location upper-left corner of the CheckBox control relative to the
upper-left corner of its form.

This property is used to get or set the space between


Margin
controls.
Property Description

This property is used to get or set the name of the


Name
control.

This property is used to get or set padding within the


Padding
control.

This property is used to get or set the text associated


Text
with this control.

This property is used to get or set the alignment of the


TextAlign text on the CheckBox control.

This property is used to get or set a value which


Visible determine whether the control and all its child controls
are displayed.

Important Events on CheckBox

Event Description

This event occur when the value of the Checked


CheckedChanged
property changes.

This event occur when the value of the CheckState


CheckStateChanged
property changes.

Click This event occur when the control is clicked.

This event occur when the user double-clicks the


DoubleClick
CheckBox control.

This event occur when the input focus leaves the


Leave
control.

This event occur when the control is clicked by the


MouseClick
mouse.
Event Description

This event occur when the user double-clicks the


MouseDoubleClick
CheckBox control.

This event occur when the mouse pointer rests on the


MouseHover
control.

Tooltips:

In Windows Forms, the ToolTip represents a tiny pop-up box which appears when you
place your pointer or cursor on the control.

The purpose of this control is it provides a brief description about the control present in the
windows form.

The ToolTip class is used to create ToolTip control and also provide different types of
properties, methods, events and also provides run time status of the controls.

You are allowed to use a ToolTip class in any container or control. With the help of a single
ToolTip component, you are allowed to create multiple tooltips for multiple controls.

The ToolTip class defined under System.Windows.Forms namespace.

In C# you can create a ToolTip in the windows form by using two different ways:

1. Design-Time:

Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a
ToolTip control programmatically with the help of syntax provided by the ToolTip class.
The following steps show how to set the create ToolTip dynamically:

Step 1: Create a ToolTip control using the ToolTip() constructor is provided by the ToolTip
class.
// Creating a ToolTip control
ToolTip t_Tip = new ToolTip();
Step 2: After creating ToolTip control, set the property of the ToolTip control provided by
the ToolTip class.
// Setting the properties of ToolTip
t_Tip.Active = true;
t_Tip.AutoPopDelay = 4000;
t_Tip.InitialDelay = 600;
t_Tip.IsBalloon = true;
t_Tip.ToolTipIcon = ToolTipIcon.Info;
t_Tip.SetToolTip(box1, "Name should start with Capital letter");
t_Tip.SetToolTip(box2, "Password should be greater than 8 words")

Constructors.
Constructor Description

This Constructors is used to initialize a new instance of the ToolTip without a


ToolTip() specified container.

This Constructors is used to initialize a new instance of the ToolTip class with
ToolTip(IContainer) a specified container.
Properties
Property Description

This property is used to get or set a value indicating whether the ToolTip is
Active currently active.

AutomaticDelay This property is used to get or set the automatic delay for the ToolTip.

This property is used to get or set the period of time the ToolTip remains visible
AutoPopDelay if the pointer is stationary on a control with specified ToolTip text.

BackColor This property is used to get or set the background color for the control.

ForeColor This property is used to get or set the foreground color of the control.

This property is used to get or set the time that passes before the ToolTip
InitialDelay appears.

This property is used to get or set a value indicating whether the ToolTip should
IsBalloon use a balloon window.
This property is used to get or set the length of time that must transpire before
subsequent ToolTip windows appear as the pointer moves from one control to
ReshowDelay another.

This property is used to get or set a value that defines the type of icon to be
ToolTipIcon displayed alongside the ToolTip text.

ToolTipTitle This property is used to get or set a title for the ToolTip window.

Mouse Events handling:


Mouse Events

There are several kinds of mouse events:

Click
This event occurs when the mouse button is released, typically before the MouseUp event.
The handler for this event receives an argument of type EventArgs. Handle this event when
you only need to determine when a click occurs.

MouseClick
This event occurs when the user clicks the control with the mouse. The handler for this event
receives an argument of type MouseEventArgs. Handle this event when you need to get
information about the mouse when a click occurs.

DoubleClick
This event occurs when the control is double-clicked. The handler for this event receives an
argument of type EventArgs. Handle this event when you only need to determine when a
double-click occurs.

MouseDoubleClick
This event occurs when the user double-clicks the control with the mouse. The handler for
this event receives an argument of type MouseEventArgs. Handle this event when you need
to get information about the mouse when a double-click occurs.

MouseDown
This event occurs when the mouse pointer is over the control and the user presses a mouse
button. The handler for this event receives an argument of type MouseEventArgs.

MouseEnter
This event occurs when the mouse pointer enters the border or client area of the control,
depending on the type of control. The handler for this event receives an argument of type
EventArgs.

MouseHover
This event occurs when the mouse pointer stops and rests over the control. The handler for
this event receives an argument of type EventArgs.

MouseLeave
This event occurs when the mouse pointer leaves the border or client area of the control,
depending on the type of the control. The handler for this event receives an argument of
type EventArgs.

MouseMove
This event occurs when the mouse pointer moves while it is over a control. The handler for
this event receives an argument of type MouseEventArgs.

MouseUp
This event occurs when the mouse pointer is over the control and the user releases a mouse
button. The handler for this event receives an argument of type MouseEventArgs.

MouseWheel
This event occurs when the user rotates the mouse wheel while the control has focus. The
handler for this event receives an argument of type MouseEventArgs. You can use the Delta
property of MouseEventArgs to determine how far the mouse has scrolled.

Example:
You can handle various Mouse actions by using the events specified in the Control class.
Following listing shows how to handle a simple MouseUp Event:

using System;
using System.Windows.Forms;
using System.Drawing;
public class Mousedemo:Form
{
public Mousedemo()
{
this.MouseUp += new MouseEventHandler(OnMouseup);
}
public void OnMouseup(object sender,MouseEventArgs e)
{
this.Text = "Current Position (" +e.X + " , " + e.Y +")";
}
public static void Main()
{
Application.Run(new Mousedemo());
}
}

Keyboard Events:
KeyDown:

The KeyDown event occurs when a key is first pressed down.


It provides the current state of the keyboard when the key was pressed.
You can handle this event to perform specific actions based on the key pressed.

KeyPress:
The KeyPress event occurs when a key is pressed and generates a character.
It provides the character representation of the key that was pressed.
You can handle this event to process character input, such as validating or filtering user
input.

KeyUp:
The KeyUp event occurs when a key is released after being pressed down.
It provides the current state of the keyboard when the key was released.
You can handle this event to perform specific actions based on the key released.
To handle these keyboard events, you need to subscribe to them for the desired control or
form.

Here's an example demonstrating how to handle keyboard events for a Windows Forms
application:
using System;
using System.Windows.Forms;

public class MyForm : Form


{
public MyForm()
{
KeyDown += MyForm_KeyDown;
KeyPress += MyForm_KeyPress;
KeyUp += MyForm_KeyUp;
}

private void MyForm_KeyDown(object sender, KeyEventArgs e)


{
// Handle KeyDown event
Console.WriteLine("Key Down: " + e.KeyCode);
}

private void MyForm_KeyPress(object sender, KeyPressEventArgs e)


{
// Handle KeyPress event
Console.WriteLine("Key Press: " + e.KeyChar);
}

private void MyForm_KeyUp(object sender, KeyEventArgs e)


{
// Handle KeyUp event
Console.WriteLine("Key Up: " + e.KeyCode);
}

// ... other code for your form


}
In the above example, we subscribe to the KeyDown, KeyPress, and KeyUp events of the
form. Inside the event handler methods (MyForm_KeyDown, MyForm_KeyPress,
MyForm_KeyUp), you can perform specific actions based on the keyboard events. The
KeyEventArgs and KeyPressEventArgs objects provide information about the key that
triggered the event.

Remember to instantiate and display an instance of the form to see the keyboard events in
action.

These keyboard events allow you to capture and respond to user input from the keyboard in
your C# application. You can customize the behavior based on the specific keys pressed or
released, enabling you to create interactive and responsive applications.
C# Menu control:
A Menu on a Windows Form is created with a MainMenu object, which is a collection of
MenuItem objects. MainMenu is the container for the Menu structure of the form and menus
are made of MenuItem objects that represent individual parts of a menu.

You can add menus to Windows Forms at design time by adding the MainMenu component
and then appending menu items to it using the Menu Designer.

After creating the Menu on the form , you have to double click on each menu item and write
the programs there depends on your requirements. The following C# program shows how
to show a messagebox when clicking a Menu item.

Example Program:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void menu1ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("You are selected MenuItem_1");
}
}
}

Some Members
CloneMenu () -- Sets this menu to be a similar copy of another menu.
MergeMenu () -- Merges an additional menus items with this one.

There are two properties named mergeType and mergeOrder


mergeType -- Determine how individual menu items are handled during a menu merge and
the relative location of each Menu Item in the newly merged menu.
mergeOrder -- Determine the menu items' presence and location within a menu merge.
GetMainMenu () -- Returns the Main Menu item that holds this menu.
MdiListItem -- This property returns the MenuItem that contains the list of MDI child
windows.

Some properties
Index -- Gets or sets the menu items position in its parent menu.
Checked -- Gets or sets a value representing whether a check mark appears nearby the text
of the menu item.
Text -- Gets or sets the text of the menu item.
Shortcut -- Gets or sets the shortcut key connected with the menu item.
Enabled -- Gets or sets a value representing whether the menu item is enabled.

Month Calendar Control:


 C# MonthCalendar Control is known as graphical interface that is used to modify and
select range of date information for required application.

 In order to create C# MonthCalendar control, open the windows form application and
go to Toolbar appearing on the left side.

 Find the MonthCalendar control, drag and drop it over the Form.
 You can play with it and move it around over the Form with the help of mouse.

 There is another way of creating the MonthCalendar control. Just double click on the
MonthCalendar control, it will automatically place the MonthCalendar control on the
Form.
Properties of Month Calendar Control.

Link Label control:


 A LinkLabel control is a label control that can display a hyperlink.
 A LinkLabel control is inherited from the Label class so it has all the functionality
provided by the Windows Forms Label control.
 LinkLabel control does not participate in user input or capture mouse or keyboard
events.

Properties:

Properties Description

Text alignment is set using this property either to right or


TextAlign
left by giving values 0 or 1
Text Property used for the label text.

Height This property is used to specify height of the control.

Width This property is used to specify the width of the control.

BackStyle Property used to make a label transparent or opaque.

Autosize Property is used to adjust the label text horizontally.

WordWrap Property is used to adjust the label vertically.

ActiveLinkColor Property used to specify the color of the active link.

DisabledLinkColor Property used to specify the color of the disabled link.

LinkColor Property is used to specify the color for a normal link.

VisitedLinkColor Property is used to specify the color for a visited link.

Events:

Events Description

LinkClicked Triggered when the link is clicked.

ListBox control:
A control that displays a list of items that a user can select. This control can be populated
with items from a data source.

It allows the programmer to add items at design time by using the properties window or at
the runtime.
 You can populate the list box items either from the properties window or at runtime.
 To add items to a ListBox, select the ListBox control and get to the properties window,
for the properties of this control.
 Click the ellipses (...) button next to the Items property.
 This opens the String Collection Editor dialog box, where you can enter the values one at
a line.

The following are some of the commonly used properties of the ListBox control −

Sr.No. Property & Description

1
AllowSelection

Gets a value indicating whether the ListBox currently enables selection of list items.

2
BorderStyle

Gets or sets the type of border drawn around the list box.

3
ColumnWidth

Gets of sets the width of columns in a multicolumn list box.

4
HorizontalExtent

Gets or sets the horizontal scrolling area of a list box.


5
HorizontalScrollBar

Gets or sets the value indicating whether a horizontal scrollbar is displayed in the list box.

6
ItemHeight

Gets or sets the height of an item in the list box.

7
Items

Gets the items of the list box.

8
MultiColumn

Gets or sets a value indicating whether the list box supports multiple columns.

9
ScrollAlwaysVisible

Gets or sets a value indicating whether the vertical scroll bar is shown at all times.

10
SelectedIndex

Gets or sets the zero-based index of the currently selected item in a list box.

11
SelectedIndices

Gets a collection that contains the zero-based indexes of all currently selected items in the list box.

12
SelectedItem

Gets or sets the currently selected item in the list box.

13
SelectedItems

Gets a collection containing the currently selected items in the list box.

14
SelectedValue

Gets or sets the value of the member property specified by the ValueMember property.
15
SelectionMode

Gets or sets the method in which items are selected in the list box. This property has values −

 None
 One
 MultiSimple
 MultiExtended

16
Sorted

Gets or sets a value indicating whether the items in the list box are sorted alphabetically.

17
Text

Gets or searches for the text of the currently selected item in the list box.

18
TopIndex

Gets or sets the index of the first visible item of a list box.

Methods of the ListBox Control


The following are some of the commonly used methods of the ListBox control −

Sr.No. Method Name & Description

1 BeginUpdate
Prevents the control from drawing until the EndUpdate method is called, while items are
added to the ListBox one at a time.

2 ClearSelected
Unselects all items in the ListBox.

3 EndUpdate
Resumes drawing of a list box after it was turned off by the BeginUpdate method.
4 FindString
Finds the first item in the ListBox that starts with the string specified as an argument.

5 FindStringExact
Finds the first item in the ListBox that exactly matches the specified string.

6 GetSelected
Returns a value indicating whether the specified item is selected.

7 SetSelected
Selects or clears the selection for the specified item in a ListBox.

8 OnSelectedIndexChanged
Raises the SelectedIndexChanged event.

8 OnSelectedValueChanged
Raises the SelectedValueChanged event.

Events of the ListBox Control


The following are some of the commonly used events of the ListBox control −

Sr.No. Event & Description

1 Click
Occurs when a list box is selected.

2 SelectedIndexChanged
Occurs when the SelectedIndex property of a list box is changed.
ComboBox control:
The ComboBox control is used to display a drop-down list of various items. It is a
combination of a text box in which the user enters an item and a drop-down list from
which the user selects an item.
Let's create a combo box by dragging a ComboBox control from the Toolbox and
dropping it on the form.

You can populate the list box items either from the properties window or at runtime.
To add items to a ComboBox, select the ComboBox control and go to the properties
window for the properties of this control.

Click the ellipses (...) button next to the Items property. This opens the String
Collection Editor dialog box, where you can enter the values one at a line.

Properties of the ComboBox Control


The following are some of the commonly used properties of the ComboBox control −

Sr.No. Property & Description

1 AllowSelection
Gets a value indicating whether the list enables selection of list items.
2 AutoCompleteCustomSource
Gets or sets a custom System.Collections .Specialized.StringCollection to use when
the AutoCompleteSourceproperty is set to CustomSource.

3 AutoCompleteMode
Gets or sets an option that controls how automatic completion works for the
ComboBox.

4 AutoCompleteSource
Gets or sets a value specifying the source of complete strings used for automatic
completion.

5 DataBindings
Gets the data bindings for the control.

6 DataManager
Gets the CurrencyManager associated with this control.

7 DataSource
Gets or sets the data source for this ComboBox.

8 DropDownHeight
Gets or sets the height in pixels of the drop-down portion of the ComboBox.

9 DropDownStyle
Gets or sets a value specifying the style of the combo box.

10 DropDownWidth
Gets or sets the width of the of the drop-down portion of a combo box.

11 DroppedDown
Gets or sets a value indicating whether the combo box is displaying its drop-down
portion.

12 FlatStyle
Gets or sets the appearance of the ComboBox.

13 ItemHeight
Gets or sets the height of an item in the combo box.

14 Items
Gets an object representing the collection of the items contained in this ComboBox.

15 MaxDropDownItems
Gets or sets the maximum number of items to be displayed in the drop-down part of
the combo box.

16 MaxLength
Gets or sets the maximum number of characters a user can enter in the editable area
of the combo box.

17 SelectedIndex
Gets or sets the index specifying the currently selected item.

18 SelectedItem
Gets or sets currently selected item in the ComboBox.

19 SelectedText
Gets or sets the text that is selected in the editable portion of a ComboBox.

20 SelectedValue
Gets or sets the value of the member property specified by the ValueMember
property.
21 SelectionLength
Gets or sets the number of characters selected in the editable portion of the combo
box.

22 SelectionStart
Gets or sets the starting index of text selected in the combo box.

23 Sorted
Gets or sets a value indicating whether the items in the combo box are sorted.

24 Text
Gets or sets the text associated with this control.

Methods of the ComboBox Control


The following are some of the commonly used methods of the ComboBox control −

Sr.No. Method Name & Description

1 BeginUpdate
Prevents the control from drawing until the EndUpdate method is called, while
items are added to the combo box one at a time.

2 EndUpdate
Resumes drawing of a combo box, after it was turned off by the BeginUpdate
method.

3 FindString
Finds the first item in the combo box that starts with the string specified as an
argument.

4 FindStringExact
Finds the first item in the combo box that exactly matches the specified string.
5 SelectAll
Selects all the text in the editable area of the combo box.

Events of the ComboBox Control


The following are some of the commonly used events of the ComboBox control −

Sr.No. Event & Description

1 DropDown
Occurs when the drop-down portion of a combo box is displayed.

2 DropDownClosed
Occurs when the drop-down portion of a combo box is no longer visible.

3 DropDownStyleChanged
Occurs when the DropDownStyle property of the ComboBox has changed.

4 SelectedIndexChanged
Occurs when the SelectedIndex property of a ComboBox control has changed.

5 SelectionChangeCommitted
Occurs when the selected item has changed and the change appears in the combo
box.

Tree View control:


The TreeView control is used to display hierarchical representations of items similar
to the ways the files and folders are displayed in the left pane of the Windows
Explorer. Each node may contain one or more child nodes.
Let's click on a TreeView control from the Toolbox and place it on the form.
Properties of the TreeView Control
The following are some of the commonly used properties of the TreeView control −

Sr.No. Property & Description

1 BackColor
Gets or sets the background color for the control.

2 BackgroundImage
Gets or set the background image for the TreeView control.

3 BackgroundImageLayout
Gets or sets the layout of the background image for the TreeView control.

4 BorderStyle
Gets or sets the border style of the tree view control.

5 CheckBoxes
Gets or sets a value indicating whether check boxes are displayed next to the tree
nodes in the tree view control.

6 DataBindings
Gets the data bindings for the control.

7 Font
Gets or sets the font of the text displayed by the control.

8 FontHeight
Gets or sets the height of the font of the control.

9 ForeColor
The current foreground color for this control, which is the color the control uses to
draw its text.

10 ItemHeight
Gets or sets the height of each tree node in the tree view control.

11 Nodes
Gets the collection of tree nodes that are assigned to the tree view control.

12 PathSeparator
Gets or sets the delimiter string that the tree node path uses.

13 RightToLeftLayout
Gets or sets a value that indicates whether the TreeView should be laid out from
right-to-left.

14 Scrollable
Gets or sets a value indicating whether the tree view control displays scroll bars
when they are needed.

15 SelectedImageIndex
Gets or sets the image list index value of the image that is displayed when a tree node
is selected.
16 SelectedImageKey
Gets or sets the key of the default image shown when a TreeNode is in a selected
state.

17 SelectedNode
Gets or sets the tree node that is currently selected in the tree view control.

18 ShowLines
Gets or sets a value indicating whether lines are drawn between tree nodes in the
tree view control.

19 ShowNodeToolTips
Gets or sets a value indicating ToolTips are shown when the mouse pointer hovers
over a TreeNode.

20 ShowPlusMinus
Gets or sets a value indicating whether plus-sign (+) and minus-sign (-) buttons are
displayed next to tree nodes that contain child tree nodes.

21 ShowRootLines
Gets or sets a value indicating whether lines are drawn between the tree nodes that
are at the root of the tree view.

22 Sorted
Gets or sets a value indicating whether the tree nodes in the tree view are sorted.

23 StateImageList
Gets or sets the image list that is used to indicate the state of the TreeView and its
nodes.

24 Text
Gets or sets the text of the TreeView.
25 TopNode
Gets or sets the first fully-visible tree node in the tree view control.

26 TreeViewNodeSorter
Gets or sets the implementation of IComparer to perform a custom sort of the
TreeView nodes.

27 VisibleCount
Gets the number of tree nodes that can be fully visible in the tree view control.

Methods of the TreeView Control


The following are some of the commonly used methods of the TreeView control −

Sr.No. Method Name & Description

1 CollapseAll
Collapses all the nodes including all child nodes in the tree view control.

2 ExpandAll
Expands all the nodes.

3 GetNodeAt
Gets the node at the specified location.

4 GetNodeCount
Gets the number of tree nodes.

5 Sort
Sorts all the items in the tree view control.

6 ToString
Returns a string containing the name of the control.
Events of the TreeView Control
The following are some of the commonly used events of the TreeView control −

Sr.No. Event & Description

1 AfterCheck
Occurs after the tree node check box is checked.

2 AfterCollapse
Occurs after the tree node is collapsed.

3 AfterExpand
Occurs after the tree node is expanded.

4 AfterSelect
Occurs after the tree node is selected.

5 BeforeCheck
Occurs before the tree node check box is checked.

6 BeforeCollapse
Occurs before the tree node is collapsed.

7 BeforeExpand
Occurs before the tree node is expanded.

8 BeforeLabelEdit
Occurs before the tree node label text is edited.

9 BeforeSelect
Occurs before the tree node is selected.
10 ItemDrag
Occurs when the user begins dragging a node.

11 NodeMouseClick
Occurs when the user clicks a TreeNode with the mouse.

12 NodeMouseDoubleClick
Occurs when the user double-clicks a TreeNode with the mouse.

13 NodeMouseHover
Occurs when the mouse hovers over a TreeNode.

14 PaddingChanged
Occurs when the value of the Padding property changes.

15 Paint
Occurs when the TreeView is drawn.

16 RightToLeftLayoutChanged
Occurs when the value of the RightToLeftLayout property changes.

17 TextChanged
Occurs when the Text property changes.

ListView control:

The ListView control is used to display a list of items. Along with the TreeView
control, it allows you to create a Windows Explorer like interface.

Let's click on a ListView control from the Toolbox and place it on the form.
 The ListView control displays a list of items along with icons. The Item property
of the ListView control allows you to add and remove items from it.
 The SelectedItem property contains a collection of the selected items.
 The MultiSelect property allows you to set select more than one item in the list
view.
 The CheckBoxes property allows you to set check boxes next to the items.

Properties of the ListView Control


The following are some of the commonly used properties of the ListView control −

Sr.No Property & Description

1 Alignment
Gets or sets the alignment of items in the control.

2 AutoArrange
Gets or sets whether icons are automatically kept arranged.

3 BackColor
Gets or sets the background color.

4 CheckBoxes
Gets or sets a value indicating whether a check box appears next to each item in the
control.
5 CheckedIndices
Gets the indexes of the currently checked items in the control.

6 CheckedItems
Gets the currently checked items in the control.

7 Columns
Gets the collection of all column headers that appear in the control.

8 GridLines
Gets or sets a value indicating whether grid lines appear between the rows and
columns containing the items and subitems in the control.

9 HeaderStyle
Gets or sets the column header style.

10 HideSelection
Gets or sets a value indicating whether the selected item in the control remains
highlighted when the control loses focus.

11 HotTracking
Gets or sets a value indicating whether the text of an item or subitem has the
appearance of a hyperlink when the mouse pointer passes over it.

12 HoverSelection
Gets or sets a value indicating whether an item is automatically selected when the
mouse pointer remains over the item for a few seconds.

13 InsertionMark
Gets an object used to indicate the expected drop location when an item is dragged
within a ListView control.
14 Items
Gets a collection containing all items in the control.

15 LabelWrap
Gets or sets a value indicating whether item labels wrap when items are displayed in
the control as icons.

16 LargeImageList
Gets or sets the ImageList to use when displaying items as large icons in the control.

17 MultiSelect
Gets or sets a value indicating whether multiple items can be selected.

18 RightToLeftLayout
Gets or sets a value indicating whether the control is laid out from right to left.

19 Scrollable
Gets or sets a value indicating whether a scroll bar is added to the control when there
is not enough room to display all items.

20 SelectedIndices
Gets the indexes of the selected items in the control.

21 SelectedItems
Gets the items that are selected in the control.

22 ShowGroups
Gets or sets a value indicating whether items are displayed in groups.
23 ShowItemToolTips
Gets or sets a value indicating whether ToolTips are shown for the ListViewItem
objects contained in theListView.

24 SmallImageList
Gets or sets the ImageList to use when displaying items as small icons in the control.

25 Sorting
Gets or sets the sort order for items in the control.

26 StateImageList
Gets or sets the ImageList associated with application-defined states in the control.

27 TopItem
Gets or sets the first visible item in the control.

28 View
Gets or sets how items are displayed in the control. This property has the following
values:

 LargeIcon − displays large items with a large 32 x 32 pixels icon.


 SmallIcon − displays items with a small 16 x 16 pixels icon
 List − displays small icons always in one column
 Details − displays items in multiple columns with column headers and fields
 Tile − displays items as full-size icons with item labels and sub-item
information.

29 VirtualListSize
Gets or sets the number of ListViewItem objects contained in the list when in virtual
mode.

30 VirtualMode
Gets or sets a value indicating whether you have provided your own data-
management operations for the ListView control.
Methods of the ListView Control
The following are some of the commonly used methods of the ListView control −

Sr.No. Method Name & Description

1 Clear
Removes all items from the ListView control.

1 ToString
Returns a string containing the string representation of the control.

Events of the ListView Control


The following are some of the commonly used events of the ListView control −

Sr.No. Event & Description

1 ColumnClick
Occurs when a column header is clicked.

2 ItemCheck
Occurs when an item in the control is checked or unchecked.

3 SelectedIndexChanged
Occurs when the selected index is changed.

4 TextChanged
Occurs when the Text property is changed.

C# Tab control:
The TabControl manages tab pages where each page may host different child
controls. In this article, I will demonstrate how to create and use a TabControl in
Windows Forms.
Design time inclusion of Tab control:
To create a TabControl control at design-time, you simply drag and drop a
TabControl control from Toolbox onto a Form in Visual Studio. After you drag and
drop a TabControl on a Form, the TabControl1 is added to the Form and looks like
Figure 1.

A TabControl is just a container and has no value without tab pages. As you can see
from Figure 1, by default two Tab Pages are added to the TabControl. We can add
and remove tab pages by clicking on the Tasks handle and selecting Add and
Remove Tab links as you see in Figure 2.

Multiple Document Interface(MDI forms):


MDI stands for Multiple Document Interface applications that allow
users to work with multiple documents by opening more than one
document at a time. Whereas, a Single Document Interface (SDI)
application can manipulate only one document at a time.
The MDI applications act as the parent and child relationship in a form.
A parent form is a container that contains child forms, while child forms
can be multiple to display different modules in a parent form.

VB.NET has folowing rules for creating a form as an MDI form.


MidParent: The MidParent property is used to set a parent form to a
child form.
ActiveMdiChild: The ActiveMdiChild property is used to get the
reference of the current child form.
IsMdiContainer: The IsMdiContainer property set a Boolean value to
True that represents the creation of a form as an MDI form.
LayoutMdi(): The LayoutMdi() method is used to arrange the child
forms in the parent or main form.
Controls: It is used to get the reference of control from the child form.
Windows Presentation Foundation:
 Windows Presentation Foundation(WPF) is a development framework used to
create a desktop application.
 It is a part of the .NET framework. The WPF has a resolution-independent and
vector-based rendering engine which is helpful to deal with modern graphics
hardware.
 The latest version of WPF is 4.6. In this framework, UI of the application is
designed in XAML language and Application logic is Written in C#
programming language.
 WPF is a successor of Windows Forms.
 Earlier Windows Forms uses the Windows Graphics Device Interface (GDI+) for
rendering any graphics, and drawing text.
 WPF is a new framework for developing rich Windows smart client applications
that uses the DirectX technology behind the scene.
 WPF is resolution-independent because WPF uses vector graphics for drawing
the controls on the screen.
 For example, a simple Checkbox control in WPF contains its vector graphics
instructions that describe the render definition of control.
 WPF uses the hardware acceleration for better graphics and better performance.

Sr. Controls & Description


No.

1 Button
A control that responds to user input

2 Calendar
Represents a control that enables a user to select a date by using a visual
calendar display.

3 CheckBox
A control that a user can select or clear.

4 ComboBox
A drop-down list of items a user can select from.

5 ContextMenu
Gets or sets the context menu element that should appear whenever the
context menu is requested through user interface (UI) from within this
element.

6 DataGrid
Represents a control that displays data in a customizable grid.

7 DatePicker
A control that lets a user select a date.

8 Dialogs
An application may also display additional windows to help the user
gather or display important information.
9 GridView
A control that presents a collection of items in rows and columns that can
scroll horizontally.

10 Image
A control that presents an image.

11 Label
Displays text on a form. Provides support for access keys.

12 ListBox
A control that presents an inline list of items that the user can select from.

13 Menus
Represents a Windows menu control that enables you to hierarchically
organize elements associated with commands and event handlers.

14 PasswordBox
A control for entering passwords.

15 Popup
Displays content on top of existing content, within the bounds of the
application window.

16 ProgressBar
A control that indicates progress by displaying a bar.

17 RadioButton
A control that allows a user to select a single option from a group of
options.

18 ScrollViewer
A container control that lets the user pan and zoom its content.

19 Slider
A control that lets the user select from a range of values by moving a
Thumb control along a track.
20 TextBlock
A control that displays text.

21 ToggleButton
A button that can be toggled between 2 states.

22 ToolTip
A pop-up window that displays information for an element.

23 Window
The root window which provides minimize/maximize option, Title bar,
border and close button

24 3rd Party Controls


Use third-party controls in your WPF applications.

WPF Architecture
The architecture of WPF can be classified into three layers,

Managed Layer

Unmanaged Layer

Core API Layer

(Image is taken from Google)

Managed Layer

This layer contains Presentation Framework and the Presentation Core, which is
basically part of .Net framework and written in managed code, hence called
managed layer. All the managed code management is managed by CLR itself.
Basically, three DLL files -PresentationFramework.dll, PresentationCode.dll, and
WindowsBase.dll build the make part of WPF Architecture.
On creating the WPF application, you will see these into the solution file.

PresentationFramework.dll

This DLL consists of all classes that are required to create the WPF UI. This wraps up
the controls, data bindings, styling, shapes, media, documents, annotations,
animation and more.

PresentationCore.dll
Presentation Core acts as a managed wrapper around MILCore and provides a
public interface for MIL. This is a low-level API exposed by WPF providing features
for 2D, 3D, geometry and so on. Presentation Core provides classes for creating
application visual tree. The Visual System creates a visual tree which contains
applications Visual Elements and rendering instructions. PresentationCore.dll is
responsible for this purpose.

WindowsBase.dll
WindowsBase.dll assembly holds the most basic and most important types in WPF
like DependencyObject, DependencyProperty, DispatcherObject and
DispatcherTimer.

These classes are the base of WPF. The main classes exist in System.Windows
namespace and System.Windows.Threading namespaces.

Unmanaged Layer
This layer has two segments.

MilCore
WindowsCodecs
This layer is also called MilCore (Media Integration Library).
MilCore (Media Integration Library)

Milcore is a part of the unmanaged code which allows tight integration with DirectX
(responsible for display and rendering). All rendering of controls in WPF is done
through DirectX engine. DirectX is a collection of API developed by Microsoft for
graphics, 2D, 3D programs.

WindowsCodecs
WindowsCodecs provides Imaging support in WPF. Image display, processing,
scaling and transform are all handled by WindowsCodecs

Core API Layer


This layer has OS core components like Kernel, User32, GDI, Device Drivers,
Graphic cards etc. These components are used by the application to access low-level
APIs. User32 manages memory and process separation.

DirectX
DirectX is the low-level API through which WPF renders all graphics. DirectX talks
with drivers and renders the content.

User32
User32 actually manages memory and process separation. It is the primary core API
that every application uses. User32 decides which element will be placed where on
the screen.

GDI
GDI stands for Graphic Device Interface. GDI provides an expanded set of graphics
primitives and a number of improvements in rendering quality.
CLR
WPF leverages the full .NET Framework and executes on the Common Language
Runtime (CLR).

Device Drivers
Device Drivers are specific to the operating system. Device Drivers are used by the
applications to access low-level APIs.

WPF Architecture (Explanation)


WPF Architecture:

 The major components of the WPF are PresentationFramework,


PresentationCore, Milcore, Common Language Runtime(CLR), User32, Kernel.
 Milcore is written in unmanaged code in order to enable tight integration with
DirectX, which is responsible for display.
 WPF has fine control over memory and execution.
 The composition engine in milcore is extremely performance-sensitive and
required giving up many advantages of the Common Language Runtime to gain
performance.

WPF Architecture consists of two layers:

 Managed Layer
 Unmanaged Layer

Managed Layer: Managed Layer composed of three assemblies:

 WindowsBase
 PresentationFramework
 PresentaionCore
1. WindowsBase: WindowsBase assembly defines the most basic and most
important types in WPF like DependencyObject, DependencyProperty,
DispatcherObject, DispatcherTimer.These classes are the base of WPF. The main
classes exists in System.Windows namespace and System.Windows.Threading
namespaces.

2. PresentationCore: PresentationCore provides a managed wrapper around


unmanaged code(MilCore) used in WPF. It contains all the basic visual types in
WPF. PresentationCore contains the UIElement class from which all the visual
controls inherit.
3. PresentationFramework: PresentationFramework contains all the UI controls like
Button, CheckBox, TextBlock, Label, TextBox etc. and Application class,
DataTemplate class, ControlTemplate class, All types of Triggers, Binding classes,
and all important classes for developing the UI of WPF application.

Unmanaged Layer: Managed Layer composed of two DLLs:


 MilCore
 WindowsCodecs
1. MilCore(Media Integration Library): MilCore DLL contains the unmanaged code
written for direct interaction with DirectX. All rendering of controls in WPF is done
through DirectX engine.

DirectX is a collection of API developed by Microsoft for graphics, 2D, 3D programs.


Direct allows you to write hardware independent instructions.

2. WindowsCodecs: WindowsCodecs provides Imaging support in WPF. Image


display, processing, scaling and transform are all handled by WindowsCodecs.

Features of WPF are as following:


 Extensible Application Markup Language (XAML)
 Controls
 Data Binding
 Layout
 2D and 3D graphics
 Animation
 Styles
 Templates
 Documents
 Media
 Text
 Typography

Advantages of WPF:
 The ability to make very rich UIs relatively easily.
 Easier animation and special effects
 Inherent scalability
 It uses current standard because it is newer
 the developers of the controls will likely be more focused on WPF because it’s
XAML makes it easy to create and edit your UI and allows the development
work to be separated between a designer (XAML) and a programmer (C#).
 Databinding is used to make a clean separation between data and layout.
 Uses hardware efficiently for drawing the UI, for better performance.
 It is used to make user interfaces for both Windows applications and web
applications.

Disadvantages :
* WPF's in-box control suite is far more limited than that of WinForms.
* There's greater support in the 3rd-party control space for WinForms. (That's
changing, but for now by advantage of time, WinForms has greater support in the
community).
* Most developers already know WinForms; WPF provides a new learning curve.

* WPF will not run on Windows 2000 or lower.

* No MDI child mode.

First WPF Application:


Here is a small demonstration to develop a simple Hello World WPF application. So
let’s start the simple implementation by following the steps given below.

Click on File > New > Project menu option.


The following dialog box will be displayed.

 Under Templates, select Visual C# and in the middle panel, select WPF
Application.
 Give the project a name. Type HelloWorld in the name field and click the OK
button.
 By default, two files are created, one is the XAML file (mainwindow.xaml) and the
other one is the CS file (mainwindow.cs)
 On mainwindow.xaml, you will see two sub-windows, one is the design window
and the other one is the source (XAML) window.
 In WPF application, there are two ways to design an UI for your application. One
is to simply drag and drop UI elements from the toolbox to the Design Window.
The second way is to design your UI by writing XAML tags for UI elements. Visual
Studio handles XAML tags when drag and drop feature is used for UI designing.
 In mainwindow.xaml file, the following XAML tags are written by default.

<Window x:Class = "HelloWorld.MainWindow"


xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"

Title = "MainWindow" Height = "350" Width = "604">

<Grid>
</Grid>

</Window>

By default, a Grid is set as the first element after page.

Let’s go to the toolbox and drag a TextBlock to the design window.


You will see the TextBlock on the design window.

 When you look at the source window, you will see that Visual Studio has
generated the XAML code of the TextBlock for you.
 Let’s change the Text property of TextBlock in XAML code from TextBlock to
Hello World.

<Window x:Class = "HelloWorld.MainWindow"


xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "604">

<Grid>
<TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"
Margin = "235,143,0,0" TextWrapping = "Wrap" Text = "Hello World!"
VerticalAlignment = "Top" Height = "44" Width = "102" />
</Grid>
</Window>

• Now, you will see the change on the Design Window as well.
When the above code is compiled and executed, you will see the following window.

Congratulations! You have designed and created your first WPF application.

Using XAML in WPF 4.0 Applications:


One of the first things you will encounter while working with WPF is XAML. \
XAML stands for Extensible Application Markup Language.
It’s a simple and declarative language based on XML.

In XAML, it very easy to create, initialize, and set properties of objects with
hierarchical relations.

It is mainly used for designing GUIs, however it can be used for other purposes as
well, e.g., to declare workflow in Workflow Foundation.
Contents of XAML:
Basic Syntax

When you create your new WPF project, you will encounter some of the XAML code
by default in MainWindow.xaml as shown below.

<Window x:Class = "Resources.MainWindow"


xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "525">
<Grid>
</Grid>
</Window>
The above XAML file contains different kinds of information. The following table
briefly explains the role of each information.

Information Description

<Window It is the opening object element or


container of the root.

x:Class = "Resources.MainWindow" It is a partial class declaration which


connects the markup to the partial class
code defined behind.

xmlns Maps the default XAML namespace for


= "http://schemas.microsoft.com/win WPF client/framework
fx/2006/xaml/presentation"

xmlns:x XAML namespace for XAML language


= "http://schemas.microsoft.com/w which maps it to x: prefix
infx/2006/xaml"

> End of object element of the root

<Grid> It is starting and closing tags of an empty


grid object.
</Grid>

</Window> Closing the object element

The syntax rules for XAML is almost similar to XML.


If you look at an XAML document, then you will notice that it is actually a valid
XML file, but an XML file is not necessarily an XAML file.

It is because in XML, the value of the attributes must be a string while in XAML, it
can be a different object which is known as Property element syntax.

The syntax of an Object element starts with a left angle bracket (<) followed by the
name of an object, e.g. Button.
Define some Properties and attributes of that object element.

The Object element must be closed by a forward slash (/) followed immediately by a
right angle bracket (>).

Example of simple object with no child element


<Button/>

Example of object element with some attributes


<Button Content = "Click Me" Height = "30" Width = "60" />

Example of an alternate syntax do define properties (Property element syntax)


<Button>

<Button.Content>Click Me</Button.Content>

<Button.Height>30</Button.Height>

<Button.Width>60</Button.Width>
</Button>

Example of Object with Child Element: StackPanel contains Textblock as child


element
<StackPanel Orientation = "Horizontal">
<TextBlock Text = "Hello"/>

</StackPanel>

Why XAML in WPF


XAML is not only the most widely known feature of WPF, but it's also one of the
most misunderstood features. If you have exposure to WPF, then you must have
heard of XAML; but take a note of the following two less known facts about XAML −

 WPF doesn't need XAML


 XAML doesn't need WPF

They are in fact separable pieces of technology. To understand how that can be, let's
look at a

<Window x:Class = "WPFXAMLOverview.MainWindow"


xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "604">

<StackPanel>
<Button x:Name = "button" Content = "Click Me" HorizontalAlignment = "Left"
Margin = "150" VerticalAlignment = "Top" Width = "75" />
</StackPanel>

</Window> simple example in which a button is created with some properties in


XAML.

In case you choose not to use XAML in WPF, then you can achieve the same GUI
result with procedural language as well. Let’s have a look at the same example, but
this time, we will create a button in C#.

using System.Windows;

using System.Windows.Controls;

namespace WPFXAMLOverview {

/// <summary>

/// Interaction logic for MainWindow.xaml


/// </summary>

public partial class MainWindow : Window {


public MainWindow() {

InitializeComponent();

// Create the StackPanel

StackPanel stackPanel = new StackPanel();

this.Content = stackPanel;

// Create the Button

Button button = new Button();

button.Content = "Click Me";

button.HorizontalAlignment = HorizontalAlignment.Left;
button.Margin = new Thickness(150);

button.VerticalAlignment = VerticalAlignment.Top;

button.Width = 75;

stackPanel.Children.Add(button);
}

When you compile and execute either the XAML code or the C# code, you will see
the same output as shown below.
From the above example, it is clear that what you can do in XAML to create,
initialize, and set properties of objects, the same tasks can also be done using code.

 XAML is just another simple and easy way to design UI elements.


 With XAML, it doesn’t mean that what you can do to design UI elements is the
only way. You can either declare the objects in XAML or define them using code.
 XAML is optional, but despite this, it is at the heart of WPF design.
 The goal of XAML is to enable visual designers to create user interface elements
directly.
 WPF aims to make it possible to control all visual aspects of the user interface
from mark-up.

XAML – Markup Extensions:


In XAML applications, markup extensions are a method/technique to gain a value
that is neither a specific XAML object nor a primitive type. Markup extensions can be
defined by opening and closing curly braces and inside that curly brace, the scope of
the markup extension is defined.

Data binding and static resources are markup extensions. There are some predefined
XAML markup extensions in System.xaml which can be used.

Let’s have a look at a simple example where StaticResources markup extension is


used which is a predefined XAML markup extension.

You might also like