C# & Windows Forms
Applications
Contents
Contrast btw the functions of Windows applications and console
applications
GUI - graphical user interfaces
Windows forms and form properties
Control objects such as buttons, labels, and text boxes to a form
Windows Based Applications
Windows applications function differently from console applications.
Windows applications look differently from console applications.
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
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
Graphical User Interfaces
Windows applications also look different 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.)
Elements of Good Design
Appearance matters
◦ Human-computer interaction (HCI)
Design considerations
◦ Consistency
◦ Alignment
◦ Avoid clutter
◦ Color
◦ Target audience
Use Visual Studio to Create Windows-
Based Applications
Select
File
New Windows
Project Forms Browse
Application to
template location
to store
your
Name
work
Visual Studio New Windows application
Windows-Based Applications
Propertie
s Window
Toolbox Design View
Initial design screen
Windows-Based Applications (continued)
Windows Based Applications
Main Elements:
◦ Windows Forms
◦ Events
◦ Controls
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
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.
Windows Form Properties
Property value
Properties
Figure 9-5 Properties window
C# PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN
13
Windows Form Properties (change
values at run time)
Can set properties using
program statements
◦ The fig shows properties set
using Properties window
Selecting Code on View menu
shows associated code
Form1 property changes
Inspecting the Code
Generated by Visual Studio
Three source code files ending
with a .cs extension are part of
the application
Expand Form1.cs
node to reveal the
Form1.Designer.cs
file
Solution Explorer window
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
public Form1( )
{
// Required for Windows Form Designer support.
InitializeComponent( );
}
This is the file where event handler methods will be placed
17
using System.Windows.Forms; New // Line 1
namespace Windows0 namespace
{ Base class referenced
public class Form1 : Form // Line 2
{
Constructor
public Form1( ) // Line 3
{
this.Text = "Simple Windows Application"; // Line 4
Sets
title }
} bar
}caption
Inspecting the Code - Form1.cs
Output
generated
from last
code
Inspecting the Code -
Form1.Designer.cs
InitializeComponent( ) method included here
#region Windows Form Designer generated code preprocessor directive
◦ // do not modify the contents of this method with the Code Editor
◦ Keyword “this.” precedes property name
◦ Refers to current instance of the class
◦ #endregion // Ends the preprocessor directive
InitializeComponent( ) Method
Some of the auto BackColor = Color.FromArgb (((Byte)(255)),
generated code in the ((Byte)(224)), ((Byte)(192)));
method Font = new Font("Arial", 12F, FontStyle.Bold,
◦ Added as default values GraphicsUnit.Point, ((Byte)(0)));
for properties or from ForeColor = Color.Blue;
changing property values
Location = new Point(30, 30);
Margin = new Padding(4);
MaximizeBox = false;
Name = "Form1";
StartPosition = FormStartPosition.CenterScreen;
Text = "First Windows Application";
Windows Form Events
Windows Form Events
Windows Form Events
Add code to respond to events
◦ 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
Windows Form Properties
Events
button
selected
Windows Form – Load Event
Code automatically added to register event
Code automatically added for method heading
private void Form1_Load(object sender, EventArgs e)
{
}
You add statement to event-handler method body
this.BackColor = Color.Azure;
Windows Form – FormClosing Event
Code automatically added to register event
Code automatically added for method heading
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
You add statement to event-handler method body
MessageBox.Show("Hope you are having fun!");
Running the Windows Application
No changes needed Output
in the file that has produced
Main( ) when the
Run like you do Close button
console applications causes the
(F5 or Ctrl+F5) event-handler
method to
fire
Windows Form Controls
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
Standard Controls
Windows Forms controls
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
Properties of the Control class
Systems.Windows.Forms.Control class properties
Properties of the Control class
(continued)
Table 9-2 Systems.Windows.Forms.Control properties (continued)
Methods of the Control class
Control class has over 75 properties and over 100 methods
◦ Not all are useful for every class that derives from it
A short list of
some of the many
methods.
Explore MSDN
documentation
for more
Systems.Windows.Forms.Control methods
Controls (continued)
GUI controls
Label Objects
Provide descriptive text or labels for other controls
Instantiate object
Label labelName = new Label( );
Set property values (some from Control class)
◦ Text; TextAlign; Font; Location
Add control to Form
this.Controls.Add(labelName);
Creating a TaxApp
TaxApp Form1 properties
Properties set for the Form
container
Creating a TaxApp Form
Add Label
objects to
Form
object…
Use
options on
FORMAT
menu
Formatting Label objects
Adding Labels to TaxApp Form
Add Label objects, then set
their properties using the
Properties window
(View Properties window)
TaxApp label5 object properties
TextBox Objects
Used to enter data or display text during run time
◦ Used for both input and output
Instantiate object
TextBox textBoxName = new TextBox( );
Add control to Form
this.Controls.Add(TextBoxName);
Interesting properties
◦ MultiLine, ScollBars, MaxLength, PasswordChar, CharacterCasing
TextBox Objects (continued)
TextBox properties
TextBox Objects (continued)
TextBox properties (continued)
Adding TextBox Objects to
TaxApp Form
Add TextBox objects,
then set their
property values
TaxApp TextBox objects property changes
Button
Enables user to click button to perform task
◦ If button has event-handler method and is registered as an event to which
your program is planning to respond, event-handler method is called
automatically when button clicked
Button object’s properties, methods, and events
◦ Inherits from Control (Table 9-2 & 9-3, slides 38-40)
◦ Text, Enabled, Focused, TabIndex
Adding Button Objects to
TaxApp Form
Add
Button
objects,
then set
their
property
values
TaxApp button1 properties
Adding Button
Objects to
TaxApp Form
(continued)
Events
Adding Button Objects to TaxApp
Form (continued)
•When you double-click on event, an event-handler method is created:
private void btnCompute_Click(object sender, System.EventArgs e)
{
}
•AND registers click event:
this.btnCompute.Click +=
new System.EventHandler(this.btnCompute_Click);
Adding Button Objects to TaxApp
Form (continued)
private void btnCompute_Click(object sender, System.EventArgs e)
{
string inValue;
double purchaseAmt, percent, ans;
inValue = txtPurchase.Text;
while (double.TryParse(txtPurchase.Text,out purchaseAmt)==false)
{
MessageBox.Show("Value entered must be numeric");
txtPurchase.Text = "0.0";
txtPurchase.Focus();
}
// end of source code for this method – see next slide
Adding Button Objects to
TaxApp Form (continued)
btnCompute_Click( ) ( … continued)
inValue = label5.Text; //inValue previously declared as string
Parse( ) used
inValue = inValue.Remove(inValue.Length-1, 1); here as opposed
to TryParse( )
…since value is
percent = double.Parse(inValue) / 100; being retrieve
ans = (purchaseAmt * percent) + purchaseAmt; from TextBox
txtTotalDue.Text = String.Format("{0:C}", ans).ToString();
}
TaxApp Form
AcceptButton
property on the
form
was set to
btnCompute
Tax calculator output