Lecture 6
Lecture 6
Lecture 6
Lecture Contents
Using C# &
Contrasting Visual Studio
Graphical
Windows to Create Windows
User Controls
and Console Windows Forms
Interfaces
Applications based
Applications
Contrasting Windows and Console Applications
• Console applications
• Each line in Main( ) method executed sequentially – then the program halts
• Method calls might branch to different locations in the program, however
control always returns back to Main
• Program initiates interaction with the user by calling the OS to get data using
ReadLine() method
• Program calls OS to output data through method calls like WriteLine()
or Write()
• Console applications run IPO model of computing process
Contrasting Windows and Console Applications
• Windows applications
• Instead of the program executing sequential statements from top to bottom,
the application, once launched, sits in what is called a process loop and
waits for an event
• Sits in a process loop, waiting for event to execute
• Windows applications run Event-driven model of a computing
process
Contrasting Windows and Console Applications
Output
generated
from
Windows0
application
Windows-based form
Elements of Good Design
• Appearance matters
• Human-computer interaction (HCI) research
• Design considerations
• Consistency
• Alignment
• Avoid clutter
• Color
• Target audience
Using C# & Visual Studio to Create
Windows based Applications
• Primitive approach
• Manually create Win based application in C# using a
text editor like Notepad, or Textpad etc
• Professional approach
• Using IDE like MS Visual Studio
• Select File Menu: New >> Project
• Select Visual C#, Windows and Windows Forms
Application from Visual Studio Installed Templates
pane, see next 3 slides
Use Visual Studio to Create Windows-Based
Applications
Select
File
New Windows
Project Forms Browse
Application to
template location
to store
your
Name work
Properties
Window
Design View
Dockable windows
Windows Based Applications
• MS VS automatically generates code to create a blank
Windows Form object. The IDE opens the Form Designer
pane showing the form
• If you see Code Editor pane instead, you press Shift+F7 to
view Designer. F7 reveals Code Editor
• Other panes used at application design time: Toolbox,
Solution Explorer, Properties
• Other panes used at application run time: Error List pane
and Output pane
• Pushpin icon and dockable panes (auto hide state)
Windows Based Applications
• How to run Windows based application?
• Like console applications
• Select from Debug menu
• Start Debugging (shortcut F5)
• Or
• Start Without Debugging (Ctrl+F5)
Windows Forms
• Extensive collection of Control classes
• Top-level window for an application is called a Form
• Each control has large 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
Windows Form Properties
Property value
Properties
Properties window
Windows Form Properties (continued)
Windows Forms
• Task: Modify the PureFCLForm application
• Find appropriate property and type a new value
• Change the following Form properties:
• Text
• BackColor
• Size
• FormBorderStyle
Windows Form Events
• Add code to respond to events, like button clicks
• 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 (continued)
Events
button
selected
Form1 events
Windows Form – Closing Event
• Code automatically added to register event
this.Closing += new System.ComponentModel.CancelEventHandler
(this.Form1_Closing);
• Code automatically added for method heading
private void Form1_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
}
• You add statement to event-handler method body
MessageBox.Show("Hope you are having fun!");
Windows Forms
• Task: Modify the PureFCLForm application
• Write your user reaction (fill the body of corresponding event handlers
with C# statements) in order to process the following events associated
with the form:
• Load form event
• Mouse entering form event
• For example, type a statement like
MessageBox.Show("Message at form loading time");
MessageBox.Show("Message at mouse entering form");
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
Windows Form Events
(continued)
Expand Form1.cs
node to reveal the
Form1.Designer.cs
file
Dots
indicate
other
classes
are
derived
from the
class
GUI controls
Controls
Form
Textbox
Button
Label
Listbox
Creating Windows Applications
• We will demonstrate how to build a simple GUI interface using a text
editor
• Most of the time, the designer in Visual Studio will be used
• Doing it by hand
• Shows how it works under the hood
• Let’s you make modifications by hand
• Provides an understanding so you can create your own controls
Creating Windows Applications
• In creating a GUI application we will use
• Application – a class with static methods to control operation of an
application
• Label – a widget that can display static text or an image
• Button – a push button with a textual or image displayed. Able to respond to
mouse clicks.
Visual Studio Designer
• This is a drag and drop interface for drawing a GUI
• The code is automatically generated
• You can hook event handlers onto the events and write the code for them
• It speeds writing code
• You cannot make major modifications to the code it generates
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
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
• Mutually Exclusive
• A group is formed when the radio buttons are in the same container –
usually a group box or panel
Radio Buttons
• Checked – get/set Boolean indicating if the button is checked
• CheckedChanged – delegate invoked when the button is checked or
unchecked
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
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
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
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
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;
}
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
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
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
ToolTips
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
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
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
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
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
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
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)
DateTime
• TimeSpan Subtract(DateTime)
• int CompareTo(DateTime)
• static DateTime Parse(string)
• ToLongDateString()
• ToShortDateString()
• ToLongTimeString()
• ToShortTimeString()
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
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
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
Populating a ListBox
• Any object can be placed into a ListBox
• The display is generated by ToString()
Add
Label
objects to
Form
object,
then
format