Vous êtes sur la page 1sur 75

Chapter Three

Win Forms: GUI Programming


(Elements of Event Driven Programming)
“.NET supports two types of form-based apps, WinForms and
WebForms. WinForms are the traditional, desktop GUI apps. The
great news is that Visual Studio .NET enables quick, drag-and-
drop construction of form-based applications…”

• Event-driven, code-behind programming


• Visual Studio .NET
• WinForms
• Controls

Microsoft 2
“The main difference between the web based application and
window based application is that the web application can be
access from anywhere in the world through the internet whereas
window based application need to be install on your machine to
access.

Microsoft 3
• GUI apps are based on the notion of forms and controls…
– a form represents a window
– a form contains 0 or more controls
– a control interacts with the user

Microsoft 4
• Idea is very simple:
– individual user actions are translated into “events”
– events are passed, 1 by 1, to application for processing

GUI App

– this is how most GUIs are programmed…

Microsoft 5
 GUI = Graphical User Interface
 Allows the user to interact visually with a program
 This is the “make it pretty” part

Microsoft 6
GUI-based events

• Mouse move
• Mouse click
• Mouse double-click
• Key press
• Button click
• Menu selection
• Change in focus
• Window activation
• etc.

Microsoft 7
Code-behind

• Events are handled by methods that live behind visual interface


– known as "code-behind"
– our job is to program these methods…

Microsoft 8
Call-backs

• Events are a call from object back to us…


• How is connection made?
– setup by code auto-generated by Visual Studio

Microsoft 9
Working with Visual Studio

• In Visual Studio, you work in terms


of source files, projects & solutions

• Source files contain code


– end in .cs, .vb, etc.
• Project files represent 1 assembly
– used by VS to keep track of source files
– all source files must be in the same language
– end in .csproj, .vbproj, etc.

• Solution (*.sln) files keep track of projects


– so you can work on multiple projects

Microsoft 10
Visual Studio .Net

designer

controls

Properties
events

Microsoft 11
Visual Studio .NET (VS.NET)

• A single IDE for all forms of .NET development


– from class libraries to form-based apps to web services
– and using C#, VB, C++, J#, etc.

Microsoft 12
Basic operation

• Visual Studio operates in one of 3 modes:


1) design
2) run
design run
3) break

break

• When in doubt, check the title bar of VS…

Microsoft 13
Step 1

• Create a new project of type “Windows Application”


– a form will be created for you automatically…

Microsoft 14
Step 2 — GUI design

• Select desired controls from toolbox…


– hover mouse over toolbox to reveal
– drag-and-drop onto form
– position and resize control

Microsoft 15
GUI design cont’d…

• A simple calculator:

• Position and configure controls


– click to select
– set properties via Properties window

Microsoft 16
Step 3 — code design

• “Code behind” the form…


• Double-click the control you want to program
– reveals coding window

Microsoft 17
Step 4 — run mode

• Run!

Microsoft 18
Break mode?

• Easily triggered in this application via invalid input…

Microsoft 19
WinForms

• Another name for traditional, Windows-like


GUI applications
– vs. WebForms, which are web-based

• Implemented using FCL


– hence portable to any .NET platform

Microsoft 20
Abstraction

• FCL acts as a layer of abstraction


– separates WinForm app from underlying platform

instance of
object System.Windows.Forms.Form
FCL class

CLR

Windows OS

Microsoft 21
Form properties

• Form properties typically control visual appearance:

Form1 form;
– AutoScroll form = new Form1();
form.WindowState = FormWindowState.Maximized;
– BackgroundImage form.Show();
– ControlBox
– FormBorderStyle (sizable?)
– Icon
– Location
– Size
– StartPosition
– Text (i.e. window's caption)
– WindowState (minimized, maximized, normal)

Microsoft 22
Form methods
form.Hide();
.
• Actions you can perform on a form: .
.
form.Show();
– Activate: give this form the focus
– Close: close & release associated resources
– Hide: hide, but retain resources to show form later
– Refresh: redraw
– Show: make form visible on the screen, & activate
– ShowDialog: show modally

Microsoft 23
Form events

• Events you can respond to:


– bring up properties window
– double-click on event name

– Load: occurs just before form is shown for first time


– Closing: occurs as form is being closed (ability to cancel)
– Closed: occurs as form is definitely being closed
– Resize: occurs after user resizes form
– Click: occurs when user clicks on form's background
– KeyPress: occurs when form has focus & user presses key

Microsoft 24
Example

• Ask user before closing form:

private void Form1_Closing(object sender,


System.ComponentModel.CancelEventArgs e)
{
DialogResult r;

r = MessageBox.Show("Do you really want to close?",


"MyApp",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1);
if (r == DialogResult.No)
e.Cancel = true;
}

Microsoft 25
Controls

• User-interface objects on the form:

– labels
– buttons
– text boxes
– menus
– list & combo boxes
– option buttons
– check boxes
– etc.

Microsoft 26
Toolbox

 The controls and components of C# are found in the C# Toolbox


in Visual Studio
 Organized by functionality

 To open Toolbox (takes time!):


 Menu/Item: View>>Toolbox:

 To add a component to a Form:


- Select that component in Toolbox
- Drag it onto the Form

Microsoft 27
Properties and Methods for GUI Controls

 Each control has properties (and some


methods)
 Example properties:

 Enable
 Font
 Text
 Visible
 Example methods:

 Hide
 Select
 Show
Microsoft 28
29

Editing the Properties

• Click on the control for


which you want to
change the properties
– E.g., click on form,
button, label, etc.
• You can make these
changes in the
Properties window
located on the bottom
right

Microsoft 29
Naming Controls

• In C#, default names for controls/components are:


– button1, label1, textbox1, etc.
- not very descriptive (“generic”)

• Use better, descriptive names


– Names to have meanings that make sense

Microsoft 30
Conventions for Naming Controls - Start the
control name with...
• Control • Begin name with
– Button – btn
– TextBox – txt
– ListBox – lbox
– Label – lbl
– SaveFileDialog – sfd

• Examples of Naming Controls


– A button used to calculate a total:
– btnCalcTotal
– A textbox that allows a user to enter her name:
– txtEnterName

Microsoft 31
Abstraction

• Like forms, controls are based on classes in the FCL:


– System.Windows.Forms.Label
– System.Windows.Forms.TextBox
– System.Windows.Forms.Button
– etc. object

object

• Controls are instances of


these classes object

object

object
object

Microsoft 32
Who creates all these objects?

• Who is responsible for creating control instances?


– code is auto-generated by Visual Studio
– when form object is created, controls are then created…

Microsoft 33
Naming conventions

• Set control's name via Name property


• A common naming scheme is based on prefixes:
– cmdOK refers to a command button control
– lstNames refers to a list box control
– txtFirstName refers to a text box control

Microsoft 34
Labels

• For static display of text


– used to label other things on the form
– used to display read-only results

• Interesting properties:
– Text: what user sees
– Font: how he/she sees it

Microsoft 35
Command buttons

• For the user to click & perform a task

• Interesting properties:
– Text: what user sees
– Font: how he/she sees it
– Enabled: can it be clicked
• Interesting events:
– Click: occurs when button is "pressed"

private void cmdAdd_Click(...)


{
int i, j, k;
i = System.Convert.ToInt32( this.txtNum1.Text );
j = System.Convert.ToInt32( this.txtNum2.Text );
k = i + j;
MessageBox.Show( "Sum = " + k.ToString() );
}
Microsoft 36
Text boxes

• Most commonly used control!


– for displaying text
– for data entry

• Lots of interesting features…

Microsoft 37
Text box properties

• Basic properties:
– Text: denotes the entire contents of text box (a string)
– Modified: has text been modified by user? (True / False)
– ReadOnly: set if you want user to view text, but not modify

• Do you want multi-line text boxes?


– MultiLine: True allows multiple lines of text
– Lines: array of strings, one for each line in text box
– ScrollBars: none, horizontal, vertical, or both

Microsoft 38
Text box events

• Interesting events:
– Enter, Leave: occurs on change in focus
– KeyPress: occurs on ascii keypress
– KeyDown, KeyUp: occurs on any key combination
– TextChanged: occurs whenever text is modified

– Validating and Validated


• Validating gives you a chance to cancel on invalid input

Microsoft 39
List Boxes

• Great for displaying / maintaining list of data


– list of strings
– list of objects (list box calls ToString() to display)

Customer[] customers;
.
. // create & fill array with objects...
.

// display customers in list box


foreach (Customer c in customers)
this.listBox1.Items.Add(c);

// display name of selected customer (if any)


Customer c;
c = (Customer) this.listBox1.SelectedItem;
if (c == null)
return;
else
MessageBox.Show(c.Name);
Microsoft 40
CheckBoxes

• Labeled boxes which can be checked or unchecked


– Checked – get/set Boolean to determine if box is checked
– CheckedChanged – delegate called when the box is checked or
unchecked
• * see ListBoxDemo

Microsoft 41
41
GroupBox

• Displays a border around a group of controls


• Can have optional label controlled by Text
property
• Controls can be added by
– Placing them within the group box in the designer
– Adding to the Controls list programmatically
• * see TextBoxDemo

Microsoft 42
42
Panels

• A panel is like a group box but does not have a text label
• It contains a group of controls just like group box
– BorderStyle – get/set border style as
• BorderStyle.Fixed3D
• BorderStyle.FixedSingle
• BorderStyle.None

Microsoft 43
43
Radio Buttons

• Radio buttons are similar to checkboxes, but


– Appear slightly different
– Allow buttons to be grouped so that only one can be
checked at a time
• A group is formed when the radio buttons are
in the same container – usually a group box
or panel

Microsoft 44
44
Radio Buttons

– Checked – get/set Boolean indicating if the button is checked


– CheckedChanged – delegate invoked when the button is
checked or unchecked

– * see TextBoxDemo

Microsoft 45
45
TextBox

• This is a single line or multi-line text editor


– Multiline – get/set Boolean to make multiline
– AcceptsReturn – in a multiline box, if true then
pressing Return will create a new line. If false then
the button referenced by the AcceptButton
property of the form, will be clicked.
– PasswordChar – if this is set to a char, then the
box becomes a password box

Microsoft 46
46
TextBox

– ReadOnly – if true, the control is grayed out and will not


accept user input
– ScrollBars – determines which scrollbars will be used:
ScrollBars.None, Vertical, Horizontal, Both
– TextAlign – get/set HorizontalAlignment.Left, Center, or
Right
– TextChanged – event raised when the text is changed

Microsoft 47
47
File Dialog

• The file dialog allows you to navigate through directories and


load or save files
• This is an abstract class and you use
– OpenFileDialog
– SaveFileDialog
• You should create the dialog once and reuse it so that it will
remember the last directory the user had navigated to

Microsoft 48
48
File Dialog

• InitialDirectory – string representing


the directory to start in
• Filter – a string indicating the different
types of files to be displayed
– A set of pairs of display name and pattern separated
by vertical bars
• Windows Bitmap|*.bmp|JPEG|*.jpg|GIF|*.gif
• FilterIndex – the filter to use as an origin 1 index

Microsoft 49
49
File Dialog

• FileName – the name of the file selected


• ShowDialog – a method to show the dialog and
block until cancel or OK is clicked

if (openDialog.ShowDialog() == DialogResult.OK) {
Image img =
Image.FromFile(openDialog.FileName);
pictureBox1.Image = img;
}
• * see ImageViewer

Microsoft 50
50
Image Class

• An abstract class that can store an image


• Several concrete classes are used for
image types such as BMP, GIF, or JPG
– FromFile(string fname) – loads any
supported image format from a file
– FromStream(stream) – loads an image from a
stream
– Height – image height
– Width – image width
• *see ImageViewer

Microsoft 51
51
PictureBox Class

• This displays an image


– Image – assigned an Image object to display
– SizeMode – determines what to do if the image
does not fit into the window
• Normal
• StretchImage
• AutoSize
• CenterImage
• Zoom
• * see ImageViewer

Microsoft 52
52
ToolTips

• These are the small pop-up boxes which explain the purpose
of a control
• To use
– Create a new tooltip in the designer
– Drop the tooltip onto the form
– The tooltip will appear on a tray below the form
• * see ImageViewer

Microsoft 53
53
ToolTips

Microsoft 54
54
ToolTips

• After the tooltip appears in the tray, a new tooltip property


appears for every component
• This can be assigned different text for each component
• That text will be displayed when the mouse hovers over that
component

Microsoft 55
55
NumericUpDown

• This allows the selection of an integer from a limited


range
• Also called a spinner
– Minimum – smallest selectable value
– Maximum – largest selectable value
– Increment – size of increment per click
– Value – the selected value
– ValueChanged – event raised when the value changes
• * see DateSelector

Microsoft 56
56
MonthCalendar

• A control which displays a calendar for the


selection of a range of dates
– MinDate – the first selectable date
– MaxDate – the last selectable date
– SelectionStart – DateTime of start of selection
– SelectionEnd – DateTime of end of selection
– DateChanged – event raised when date is changed
• * see DateSelector

Microsoft 57
57
DateTimePicker

• Similar to a month calendar but


– Calendar pulls down and selection displayed
– More configurable
– Selects a single value, not a range
• Properties/methods
– Format – Long, Short, Time, Custom
– Value – DateTime value selected
– ValueChanged – event which fires when date or
time changes
• * see DateSelector

Microsoft 58
58
System.DateTime Structure

• A structure representing a date and time


• Constructors
– DateTime(int d, int m, int y)
– DateTime(int d, int m, int y, int h, int m,
int s)
• Properties
– Now – returns a DateTime object set to the current local time

Microsoft 59
59
DateTime

• Day – day from 1-31


• Month – month from 1-12
• Year – tear from 1-9999
• Hour – from 0-23
• Minute – minute from 0 -59
• Second – second from 0 -59
• Millisecond – millisecond from 0-999

Microsoft 60
60
DateTime

– DayOfWeek – get enumeration of Sunday,


Monday,…
– DayOfYear – day of year from 1 – 366
• Methods
– DateTime AddYears(double value)
– DateTime AddMonths(double value)
– DateTime AddDays(double value)
– DateTime AddHours(double value)
– DateTime AddSeconds(double value)
– DateTime AddMilliseconds(double value)

Microsoft 61
61
DateTime

– TimeSpan Subtract(DateTime)
– int CompareTo(DateTime)
– static DateTime Parse(string)
– ToLongDateString()
– ToShortDateString()
– ToLongTimeString()
– ToShortTimeString()

Microsoft 62
62
ListBox

• The ListBox presents a list of items which


can be selected
• A scrollbar is displayed if needed
– MultiColumn – displays list as multiple columns
– SelectedIndex – index of selected item
– SelectedIndices – collection of selected indices
– SelectedItem – the selected item

Microsoft 63
63
ListBox

– SelectedItems – collection of selected items


– SelectionMode – how items can be selected
• None – no selection
• One – single selection
• MultiSimple – each click selects additional item
• MultiExtended – uses shift and control keys
– Sorted – if true the items will be sorted
alphabetically

Microsoft 64
64
ListBox

– Items – a collection of items in the list box


– ClearSelected – method to clear selection
– GetSelected – returns true if the parameter passed is
selected
– SelectedIndexChanged – event when selection changes
• * see ListBoxDemo

Microsoft 65
65
Populating a ListBox

• Any object can be placed into a ListBox


• The display is generated by ToString()

for(int i = 0; i < 50; i++) {


listBox1.Items.Add(
"Item " + i.ToString());
}

Microsoft 66
66
ComboBox

• A combo box is like a list but lets you displays a selected


value.
• The list pulls down when a selection is being made.
• Options allow the selected text to be editable or to require it
to be selected from the drop-down list

Microsoft 67
67
ComboBox

• DropDownStyle –
– Simple – text is editable & list always visible
– DropDown – default indicating text is editable & user must click
to see list
– DropDownList – value is not editable & user must click to
see list
• Items – the collection of items in the list

Microsoft 68
68
ComboBox

• MaxDropDownItems – max number of items in pulldown


before scrollbar used
• SelectedIndex – index of selection
• SelectedItem – selected item
• Sorted – whether entries are sorted
• SelectedIndexChanged – event raised when selection
changes

Microsoft 69
69
Help menu

Command Description
How Do I? Contains links to relevant topics, including how to
upgrade programs and learn more about web
services, architecture and design, files and I/O,
data, debugging and more.
Search Finds help articles based on search keywords.
Index Displays an alphabetized list of topics.
Contents Displays a categorized table of contents in which
help articles are organized by topic.

Fig. 2.23 | Help menu commands.

Microsoft 70
Event Handling

 When a user interacts with a form, this causes an


event to occur
- E.g., clicking a button, typing in a textbox, etc. are events

 Events signal that certain code should be run


 To perform some actions

 Event Handler = method that runs after an event


occurs
Event Handling = the overall process of
responding to events
 All GUI controls have associated events

Microsoft 71
• The following code is for a button named btnQuit
– Function: When the button is clicked, the form closes

private void btnQuit_Click(object sender, EventArgs e)


{
this.Close();
}

Microsoft 72
73

• Suppose that you are working on


the design of Form1 (see Fig)
– You are in the Design View
• You have edited form properties
• Double-click on the Quit button
– You will be switched to the Code View
– The following method appears in the code generated for the form:
private void btnQuit_Click(object sender, EventArgs e)
{
code to be written by you can be added here (to be shown later)
}

Microsoft 73
Summary

• Event-driven programming is very intuitive for GUI apps

• Forms are the first step in GUI design


– each form represents a window on the screen
– form designer enables drag-and-drop GUI construction
• Users interact primarily with form's controls
– labels, text boxes, buttons, etc.
– implies that GUI programming is control programming

Microsoft 74
The End

Microsoft 75

Vous aimerez peut-être aussi