0% found this document useful (0 votes)
25 views

Chapter Five: Using GUI Objects and The Visual Studio IDE

The document discusses how to create and use graphical user interface (GUI) objects like message boxes and forms in a Windows application using C# and the Visual Studio integrated development environment (IDE). It covers how to display message boxes, create forms as windows, place buttons on forms, and add event handling functionality to buttons.

Uploaded by

asmeradagne
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Chapter Five: Using GUI Objects and The Visual Studio IDE

The document discusses how to create and use graphical user interface (GUI) objects like message boxes and forms in a Windows application using C# and the Visual Studio integrated development environment (IDE). It covers how to display message boxes, create forms as windows, place buttons on forms, and add event handling functionality to buttons.

Uploaded by

asmeradagne
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 62

Chapter Five

Using GUI Objects and the


Visual Studio IDE

1
Objectives
• How to create a MessageBox
• How to add functionality to MessageBox buttons
• How to create a Form
• How to create a Form that is a program’s main
window

2
Objectives

• How to place a Button on a window


• How to use the Visual Studio IDE to design a Form
• Learn about the code created by the IDE
• How to add functionality to a Button on a Form
• How to use the Visual Studio Help Search function

3
Creating a MessageBox

• A MessageBox is a GUI object that can contain text, buttons,


and symbols that inform and instruct a user
• You must use the static class method Show() to display a
message box, because its constructor is not public

4
Creating a MessageBox

• Output of MessageBox1 program

5
Creating a MessageBox

• There are many overloaded versions of the Show() method

6
Creating a MessageBox

• Arguments used with the MessageBox.Show() method

7
Adding Functionality to MessageBox Buttons

• DialogResult is an enumeration, or list of values that


correspond to a user’s potential MessageBox button selection

8
Adding Functionality to MessageBox Buttons

• Output of HamburgerAddition program


9
Creating a Form

• Forms provides an interface for collecting, displaying, and


delivering information to a user through buttons, list of
options, text fields, and other controls
• Unlike the MessageBox class, you can create an instance of
the Form class

10
Creating a Form

• Output of CreateForm1

11
Creating a Form
• You can change the appearance, size, color, and window
management features of a Form by setting its instance fields
or properties
• The Form class contains approximately 100 properties that
can be used to set various configurations of the Form class
• The ShowDialog() method displays a form as a modal dialog
box

12
Creating a Form

• CreateForm2 class and Output

13
Creating a Form that is a Program’s Main
Window
• When you create a new main window, you must complete
two steps:
– You must derive a new custom class from the base class
System.Windows.Forms.Form
– You must write a Main() method that calls the Application.Run()
method, and you must pass an instance of your newly created Form
class as an argument

14
Creating a Form that is a Program’s Main
Window

• Window1 class and the Window1 object

15
Creating a Form that is a Program’s Main
Window
• When you want to add property settings to a program’s main
window, you can do so within the class constructor

16
Creating a Form that is a Program’s Main
Window

• The Window2 object

17
Placing a Button on a Window

• A Button is a GUI object you can click to cause some action


• For a Button to be clickable, you need to use the
System.Windows.Forms.Control class

18
Placing a Button on a Window

• Output of WindowWithButton program

19
Using the Visual Studio IDE to Design a Form

• Using a text editor when programming and designing GUIs is a


very tedious and error prone task
• Just determining an attractive and useful layout in which to
position all components on your Form takes many lines of
code and a lot of trial and error
• The Visual Studio IDE provides a wealth of tools to help make
the Form design process easier

20
Understanding the Code Created by the IDE

• The automatically generated code is simply a collection of C#


statements and method calls similar to the ones created by
hand
• When you use the Designer in the IDE to design your forms,
you save a lot of typing, which reduces the errors you create
• Because the IDE generates so much code automatically, it is
often more difficult to find and correct errors in programs
created using the IDE than in programs you create by hand

21
Understanding the Code Created by the IDE

• The code automatically generated by the IDE


includes:
– using statements and namespace creation
– Declarations of forms and other objects
– Comments
– Methods and method calls

22
Elements of Good Design

• Appearance matters
– Human-computer interaction (HCI) research
• Design considerations
– Consistency
– Alignment
– Avoid Clutter
– Color
– Target Audience

23
Use Visual Studio to Create Windows-
based Applications

Select
File
New Windows
Projec Application Browse
t template to
location
to store
your
Nam work
e

Visual Studio New Windows application


24
Windows-based Applications

Switch
between
Design
and Code Propertie
view using s
View menu Window

Design View
Toolbo
x
Initial design screen
25
Windows-based Applications (continued)
pushpi
n
Propertie
s
Auto-hide

Solution
Explorer

Dynamic
Help

26
Windows Forms
• Extensive collection of Control classes
• Top-level window for an application is called a Form
• This is the top-level window class
• This class contains all other controls
• Normally, your top-level form inherits from the Form
class
• Although the class has numerous methods, most of the
time you interact with it via properties and delegates
• 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

27
Windows Form Properties
Events

Alphabetical

Categorize
d

Property
Propertie
value
s

Properties window
28
Windows Form Events
• Add code to respond to events, like button
clicks
• From the Properties window, select the
lightening 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

29
Windows Form Properties (continued)

Events
button
selecte
d

Form1 events
30
Simple Windows Application
• New with Visual Studio 2010, the 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
31
Windows Form Events (continued)

Expand
Form1.cs node
to reveal the
Form1.Designer.
cs file

Solution Explorer window


32
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
33
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

34
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

35
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

36
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

37
Radio Buttons
– Checked – get/set Boolean indicating if the
button is checked
– CheckedChanged – delegate invoked when the
button is checked or unchecked

38
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

39
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

40
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

41
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

42
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;
}

43
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

44
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

45
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

46
ToolTips

47
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

48
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

49
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

50
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

51
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

52
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

53
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)

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

55
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

56
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

57
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

58
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());
}

59
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

60
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

61
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

62

You might also like