3
Contrasting Windows and Console Applications
●Windows applications functiondifferently from console applications.
●Windows applications lookdifferently from console applications.
4
Contrasting Windows and Console Applications by
Functionality
●Console applications
○Each line in Main( ) executed sequentially –then the program halts
●Windows applications
○Once launched, sits and waits for an event
○Sits in a process loop
●Event: notification from operating system that an action, such as the user
clicking the mouse or pressing a key, has occurred
○Write event-handler methods for Windows apps
5
Graphical User Interfaces
●Windows applications also lookdifferent from console applications
●Interface: front end of a program
○Visual image you see when you run a program
●Graphical user interface (GUI) includes:
○Menus
○Text in many different colors and sizes
○Other controls (pictures, buttons, etc.)
6
Windows Applications
●Reference and import System.Windows.Forms
namespace
●Class heading definition
○Includes not only the class name, but a
colon followed by another class name
■Derived class (first class), Base class
(second class)
■public class Form1 : Form
●Derived classes inherit from base class
●No multiple inheritance within .NET languages
7
Windows Applications (continued)
●Text -property of the Form class
○A property for setting/getting title bar caption
○Can be used in constructor
●Windows forms/controls offer many properties
including Text, Color, Font, and Location
●Execution begins in Main( ) method
○Main( ) is located in Program.csfile for the
application
○Call to Run( ) method places application in
process loop
Creating a Windows Forms Application Using Visual Studio
2022
●Open the Visual Studio then Go to File -> New -> Project to create a new
project and then select the language as Visual C# from the left menu.
●Click on Windows Forms App(.NET Framework) in the middle of current
window. After that give the project name and Click OK.
Use Visual Studio to Create Windows-Based Applications
Use Visual Studio to Create Windows-Based Applications
Project Windows
usingSystem.Windows.Forms; // Line 1
namespaceWindows0
{
publicclassForm1 : Form // Line 2
{
publicForm1( ) // Line 3
{
Text = "Simple Windows Application"; // Line 4
}
staticvoidMain( )
{
Form1 winForm = newForm1( ); // Line 5
Application.Run(winForm); // Line 6
}
}
}
New
namespace
referenced
Constructor
Baseclass
Sets
title bar
caption
Starts
process
loop
Project Windows
After that following window will display which will be divided into three parts as follows:
●EditorWindoworMainWindow:Here,youwillworkwithformsandcode
editing.Youcannoticethelayoutofformwhichisnowblank.Youwilldoubleclick
theformthenitwillopenthecodeforthat.
●SolutionExplorerWindow:Itisusedtonavigatebetweenallitemsinsolution.
Forexample,ifyouwillselectafilefromthiswindowthenparticularinformation
willbedisplayedinthepropertywindow.
●PropertiesWindow:Thiswindowisusedtochangethedifferentpropertiesofthe
selecteditemintheSolutionExplorer.Also,youcanchangethepropertiesof
componentsorcontrolsthatyouwilladdtotheforms.
14
Windows Forms
●Extensive collection of Control classes
●Top-level window for an application is called a Form
●Each control has collection of properties and methods
○Select property from an alphabetized list (Properties window)
○Change property by clicking in the box and selecting or typing the new
entry at design time.
●Each control has collection of events.
Adding Controls to a Form
●ToaddcontrolstoyourWinFormsapplicationgotoToolboxtabpresentinthe
extremeleftsideofVisualStudio.Here,youcanseealistofcontrols.To
accessthemostcommonlyusedcontrolsgotoCommonControlspresentin
Toolboxtab.
●DraganddropthecontrolsthatyouneededoncreatedForm.Forexample,if
youcanaddTextBox,ListBox,Buttonetc.asshownbelow.Byclickingon
theparticulardroppedcontrolyoucanseeandchangeitspropertiespresent
intherightmostcornerofVisualStudio.
Form Controls
●Intheaboveimage,youcanseetheTextBoxisselectedanditsproperties
likeTextAlign,Fontetc.areopenedinrightmostcorner.Youcanchangeits
properties’valuesaspertheapplicationneed.
●Thecodeofcontrolswillbeautomaticallyaddedinthebackground.Youcan
checktheForm1.Designer.csfilepresentintheSolutionExplorerWindow.
Windows Form
18
Windows Form Properties
Properties
Property value
Windows Form Events
Inspecting the Code Generated by Visual Studio
●Three source code files
ending with a .cs
extension are part of the
application
20
Expand Form1.cs
node to reveal the
Form1.Designer.c
s file
21
Simple Windows Application
●IDE separates the source code into three separate files
○Form1.cs:normally this is the only one you edit
○Form1.Designer.cs:holds the auto generated code
○Program.cs:contains the Main( ) method, where execution always
begins
●Form1.cs and Form1.Designer.cs both include partial class definitions for the
Form1 class
Inspecting the Code -Form1.cs
●Number of namespaces automatically added, including
System.Windows.Forms
●Constructor calls InitializeComponent( ) method
publicForm1( )
{
// Required for Windows Form Designer support.
InitializeComponent( );
}
●This is the file where event handler methods will be placed
22
InitializeComponent( ) Method
BackColor = Color.FromArgb (((Byte)(255)),
((Byte)(224)), ((Byte)(192)));
ClientSize = newSize(392, 373);
Font = newFont("Arial", 12F, FontStyle.Bold,
GraphicsUnit.Point, ((Byte)(0)));
ForeColor = Color.Blue;
Location = new Point(30, 30);
Margin = newPadding(4);
MaximizeBox = false;
Name = "Form1";
StartPosition =
FormStartPosition.CenterScreen;
Text = "First Windows Application";
●Some of the auto
generated code in the
method
○Added as default values
for properties or from
changing property values
23
24
Windows Form Events
●Add code to respond to events, like button clicks
○Code goes into Form1.cs file
●From the Properties window, select the lightning bolt (Events)
○Double-click on the event name to generate code
■Registers the event as being of interest
■Adds a heading for event-handler method
25
Windows Form –LoadEvent
●Code automatically added to register event
●Code automatically added for method heading
private void Form1_Load(object sender, EventArgse)
{
}
●You add statement to event-handler method body
this.BackColor= Color.Azure;
26
Windows Form –FormClosingEvent
●Code automatically added to register event
●Code automatically added for method heading
private void Form1_FormClosing(object sender, FormClosingEventArgse)
{
}
●You add statement to event-handler method body
MessageBox.Show("Hope you are having fun!");
27
Controls
●Controls are all classes
○Button, Label, TextBox, ComboBox, MainMenu, ListBox, CheckBox,
RadioButton, and MonthCalendar
●Each comes with its own predefined properties and methods
●Each fires events
●Each is derived from the System.Windows.Forms.Control class
28
Controls (continued)
29
Standard Controls
30
Controls (continued)
●Two procedures to place controls
○From Toolbox, double-click on control or drag and drop
●Move, resize, and delete controls
●Format controls
○Align controls
○Make same size
○Horizontal and vertical spacing
31
Properties of the Controlclass
Properties of the Controlclass (continued)
Methods of the Controlclass
●Control classhas over 75 properties and over 100 methods
○Not all are useful for every class that derives from it
33
Systems.Windows.Forms.Controlmethods
This table
includes a short
list of some of
the many
methods.
Explore MSDN
documentation
for more
Running the Windows Form Application
●ToruntheprogramyoucanuseanF5keyorPlaybuttonpresentinthe
toolbarofVisualStudio.
●TostoptheprogramyoucanusepausebuttonpresentintheToolBar.
●YoucanalsoruntheprogrambygoingtoDebug->StartDebuggingmenuin
themenubar.
Form Components Naming
●It is a good practice to change components, to track which component you
are currently working on.
●In the previous example, names could be lblFullName, txtFullName,
btnDisply, lblDisplayName and btnClearrespectively.
38
Creating a TaxApp
Properties set for the
Form container
Table 9-4TaxApp Form1 properties
39
Creating a TaxApp Form
Add Label
objects to
Form
object…
Use
options on
FORMAT
menu
40
Adding Labels to TaxApp Form
Add Label objects, then set
their properties using the
Properties window
(View Propertieswindow)
Practical Task
Develop a simple calculator application that allowing users to perform basic
arithmetic operations such as addition, subtraction, multiplication, and division
GroupBox Component
●It is used to organize all form components in the same style.
●It can be used to set properties of all the components in the groupbox.
RadioButton, CheckBox and ComboBox
●Radio Button: Is used to select one of the available choices in a given
application.
●CheckBox: Is used to select none or all of the available options
●Combobox: Is used when you have a list of options to select from.
○To prevent users from typing,change the DropDownStyle property to DropDownList
○To type the options that you want to offer to your user, use the Items property list.
○Combobox acts like an array, the first selectedIndex(0) indicates the first item in the list.
○The selected item can be obtained by accessing the selectedItem property of the given
combo box.
Validation using ErrorProvider
●ErroProvider can be used to validate user inputs
privateboolvalidation()
{
boolisValidated= true;
if(this.textName.Text=="")
{
isValidated= false;
errorProvider1.SetError(textName, "Please Enter Your Name:");
}
else
{
errorProvider1.Clear();
}
returnisValidated;
}
Menus and Toolbars
●Navigation Menu:
○Menustrip: A navigation menu.
○You can use shortcuts
○ContextMenu: Pop up menu
■It has to be linked to a form component
○ToolStrip: Similar to Menustrip. You can use components like label, buttons, etc