Chapter 16 Graphical User Interfacesx - FTP Directory Listing

undesirabletwitterΤεχνίτη Νοημοσύνη και Ρομποτική

25 Οκτ 2013 (πριν από 3 χρόνια και 9 μήνες)

72 εμφανίσεις








Graphical User Interfaces



Objectives:

At the end of the chapter students should be able to:

1)

describe the purpose of and use
of Forms
,

2)

describe the purpose of and use
of graphical components

(controls)
,

3)

understand the use of
events and event handling
,

4)

describe the purpose and use of
graphical user interfaces
,




Contents of This Chapter



14.1
Forms


14.2
Graphical Components

(Controls)


14.
3

Events and Event Handling

14.5
Graphical User Interfaces









Chapter

16

276

Chapter 15 Types of Classes in C#




14.1
Graphic User Interface
(GUI)


In previous programs you have written, you used text based or “Console


a
pplications

that
required
all user input
was
either
text from
the keyboard

or file

and output
was

text output to the
Console screen

or file
. This is a very tedious and time consuming process. Operating system
developers realized
very early
of

this restriction and began to experiment with other ways to
communication

with their users. One of the early
and most successful,
efforts was the Graphical
User Interfaces developed for a system being developed by Xerox in their Palo Alto research lab
,
called “Xerox P
ARC,


PARC for Palo Alto Research Center.


The original sys
tem was “MACS” and the
next generation was “Alto.” In this facility t
hey developed such amazing technologies as:
l
aser
p
rinting,
SmallTalk an
Object
-
Oriented Programming
language
(OOP)

, Ethernet
d
istributed
c
omputing, Superpaint frame buffer

and CRT display
, WYSIWIG
(What You See Is What You Get)
&
file formatting,

mouse

technology and use
, relational databases,
s
olid
-
s
tate
l
asers,
g
raphical
u
ser
i
nterfaces (GUI), VLSI circuit design, Worm

disk drives
,
n
atural

language processing,
optical
st
orage,
fiber optics, collaborative workspaces and tools, encryption systems, Internet standards,
digital rights management,
just to mention a few.


A very interesting outcome of this was that a small startup company, in the
bay
area, heard of the
great th
ings being explored at Xerox PARC and made arrangements to visit the research facility.
Th
is

small startup company was Apple

Computer and the company executive was
Steve Jobs
. Jobs

and an number of his development engineers visited Xerox PARC and within a

year they released
the Lisa

and
later the
Mac

computer
s

with a
n amazing

graphical user interface
with

a two button
mouse
. What was more amazing is that Xerox PARC, just gave away most of the
their
technology.
The

“MAXC

computer was the for
e
-
runner of the
“Alto”

computer which had a
2.5 MB removable
disk,
was the for
-
runner to the
“Alto II”
computer which had
6 MHz clock, 128KB highly reliable
semiconductor memor
y. It was

the first personal computer “
first really
networked

computer

3MB
Ether
net

network. One of the
PARC
developers said of the current minicomputer like the Data
General Nova and the DEC PDP
-
11 that,


It wa
s

too hard to
coach

them to do things”
.

The
“Dorado”
computer had
cache memory,
Xerox PARC developed these and
many other
computers such as
“Dolphin”, “WildFlower”, “Dandelion”, “Dicentra”
which
used multibus IO controllers, “Dragon”
used an early form of
LSI computer
s. They developed a significant amount of i
ntegrated circuit
memory

(not core memory)
, medium scale semicondu
ctors,

pattern sensitive errors, single bit
error correction
.

One of the developers stated that,

We had all these crazy technologies.” They used
“Wire wrapped” back panels, b
it mapped memory for
their
CRT display
s
.

They even developed the
first electron
ic white board. Their goal was to produce the paperless office. They perfected
networks and used them widely, including First Voice over IP.


Their
Operating Systems
included the
Alto OS, SDD Pilot and
Cedar.
Software included and

Electronic Organ

,
Digital
Scanners, Color Printer
s
, Modem bank
s, “Andy”
real
-
time

TV. They also
perfected m
icrocode in read/write memor
ies
.
They also produced a

lot of games and music
synthesis.
Amazingly Xerox never really capitalized

(other than laser printer
s and laser
printing

technologies)

on many of the technologies they pioneered; however, other companies did such as;
Oracle, Apple,
3Com,

Apollo, Sun, Adobe


PostScript, Microsoft


Word and Office and others.

Because of Xerox PARC we have the current graphical user
interface, mouse, Ethernet networking,
object
-
oriented programming, color laser printers, and many other technologies.


Now on to WYSIWIS, i
n Console applications, we had to use loops to continually communicate with
the user; whereas, in a GUI application
the GUI Form waits for the user to press a key or
click mouse
277


button

thus
caus
ing

an event
that the application
would then

respond to. Let’s get starting by
creating a GUI or “Windows Forms Application.”


14.
2

Windows Forms Application


To creat
e

a new “Windows Forms Application” start Visual Studio
(see Fig. 1)
and select “File,”
“New,”
“Project” and
when you do this the window, as shown
in Fig. 2
,

will appear.



Figure
1

Creating a New Windows Forms Application (GUI)

In

the “New Project” dialog

(shown in Fig. 2)
,
click on “Windows” then select “Windows Forms
Application” to create a GUI application.
Insure

that
the

Location

and
Name

are what you want and
click “
OK
” to
create your GUI application. In Fig. 2, I entered for Name: “GUI_Example_1” and for
Location:

G:
\
CS1410
\
Example Code
\


for the project
s

folder directory.


278

Chapter 15 Types of Classes in C#




Figure
2

New Project Dialog

14.1.1 Form


Fig. 3 shows the Form created when
our original

application was
started
. Note that the Form has a
“Title Bar
(1)
,” an icon for the Form “Menu
(2)
,” the text “Form1
(3)
,”
and to the right, three Buttons.
These Buttons are the “Minimize
(4)
,” “Maximize/Restore
(5)
” and “Close
(6)
.” The Form also has a
“Frame
(7)
,

the Frame is
the blue lines that enclose
outside of
the entire Form. The gray area inside
the Title Bar and Frame
of the Form
is the client area
(8)
. This is working
area

for us to play in.

279



Figure
3

Windows Forms Application Form1.cs [Design]

It is important to understand that all of the GUI components
(controls),
you will see in a Windows
Forms Application
,

are really classes that have: 1) Fields of data, 2) Properties, 3) Indexers, 4)
Methods and 5) Events. So everything you know about classes and objects constructed from these
classes are used to create a GUI object

known as a control or component
. The on
ly difference is that
they have methods that know how to draw the visible graphic object on your computer display

and
events handlers
. We will discuss the details of how you work with these members in each GUI
component
.


To introduce you to
the various members in the
Form1 class, look at Fig. 4. The popup menu with
the highlighted “Properties” menu was displayed
by right
-
clicking on the Client area of the Form.
When I clicked on th
e

“Properties” menu it the
generated an event display
ing

the
“Form1
Properties” window shown in Fig. 5.







Figure
4

Popup Properties Window

1

3

4

5

6

2

7

8

X

Y

280

Chapter 15 Types of Classes in C#



Carefully review the
window that displays the
properties
,
these are

displayed in the first column of the Properties Window in Fig. 5.
These are all
properties

of our programs Form1
-

System.Windows.Forms.Form. We can set such properties as the
“Font,” “BackColor,” “Size” and “Text.” Note that the “Text” property
holds the string that is displayed
in

the Forms Title Bar. I
c
hanged
this
Text Property
to “GUI Example Form” (see Fig. 7)
. You can
also
scroll the Properties Form
up,
to the “(Name)” property and
I
changed it to “FrmExample” (see Fig. 8) which changes th
is

reference property to our Form to

“FrmExample”
.


Note that for the nam
es of all my properties, I make the first three
or four characters
that
of the
control’s

name
,

to remind me of the
control

type I’m dealing with. This has a very important use as
Intellisense
,

in Visual Studio
,

displays
the property names in
alphabetical
order
when it prompts for the
control’s

name. The
following is a list of such name prefixes:




Txt

TextBox


Lbl

Label


Btn

Button


CBox

ComboBox


RBtn

RadioButton


Chb

CheckBox


RTxt

RichTextBox


M
st

MenuStrip



Another
very useful naming convention
is to prefix all data field names with
the underscore “_”
character
. This
displays

all variables together when
Intellisense displays them for you.






Figure
5

Form1 Properties Window



Figure
6

Form1 Properties Window



281




Figure
7

Form1 Properties Window (Lower Half)

With the changes made to my Form1 “Text” property
as “GUI Example Form”
is now shown on my
Form in Fig. 8.



Figure
8

Form1 with Properties Change

14.1.
2

Client Area

With a few exceptions like the “Name” and “Text” for our Form1, most of our GUI design work will
revolve around placing various
controls (
components
)

on the Client surface.
Note that the Client
Area uses X,

Y and Z
coordinates

to place controls on its surface. The X coordinate is zero in the
upper left corner of the Client Area and the positive direction is horizontal from left to right. The Y
coordinate

is zero from the upper left corner of the Client Area

and the positive direction is
vertically down the screen. The Z direction is zero on the Client Area and moves positive from the
Client Area out of the screen towards the users, the Z coordinate is used to stack controls on the
screen.
Fig. 8 displays the

various
controls

I placed on the Client area. This was done by
opening
the “ToolBox” and double
-
clicking the desired
control
.

282

Chapter 15 Types of Classes in C#






Fig. 9 shows the “Toolbox” and the red arrow points to the
“Button” component. If you double click on the Button icon a
Button
control

will be displayed in the upper left corner of you
r

Form1 Client
A
rea.
The Button’s

N
ame property will be set to
“button
1” and its
Text property is set to “button 1” you can and
should change these
to
“BtnTest” and “Test” respectively. Make
sure you drag “button1” to the bottom of the Client area as shown
in Fig. 10 with the white bubble (3).

Fig. 10 shows the placement of


label1


inside the red circle,

textBox1


pointed by the yellow arrowhead,
“r
ichTextBox1


white bubble (1) and

list
Box
1


white bubble (2). You should
rename these to

LblName


and Text
Name


TxtName


and Text
“<none”,

RTxtDisplay


and finally

L
Box
Display.


Make sure you
drag each
control

to the area shown in Fig. 10. When you click on
one of these components it will display resize handles that allow
you to visually resize the
control
.

Each control has a Size (X,Y)
Figure
9

ToolBox of Components


coordinate and a width and
height.















Fig. 11 shows the visual
controls

renamed,
re
positioned and resized as required. Note the red
arrow is pointing to one of eight resize handles for the RichTextBox. Each component has resize
handles to allow us to size them exactly for our intended purpos
es.


14.2
Events

We mentioned earlier
,

that unlike text based applications, GUI (Windows Applications) are event
driven. Events are generated mainly by two user inputs a key press event or a mouse
left button
click event. These events are numerous and var
ied in a complex GUI, but for our purpose these two
events will suffice to illustrate event handling.
When your GUI form is first loaded
(started)
the
operating system makes a method call to your applications Main method.


using System;

Figure
10

Form Components Renamed/Resized


Figure
11

Form Client Area with Various Components


283


using
System.Collections.Generic;

using System.Windows.Forms;


namespace GUI_Example_1

{


static class Program


{


/// <summary>


/// The main entry point for the application.


/// </summary>


[STAThread]


static void Main()


{


Application.EnableVisualStyles();


Application.SetCompatibleTextRenderingDefault(false);


Application.Run(new FrmExample());


}


}

}


The call to Main in
the
code above
,

sets
up the Application static class to allow your GUI form to do various
things and then calls the
Application.Run(new FrmExample());

method which calls the new operator
creating the
FrmExmple

object on the Heap and calling the
FrmExample

constructor which con
structs our
form object, initializes all our components and displays the form on our computer screen. The form now waits
for events. I double clicked
the

Button “Test” and this generated the event handling method below:


private void BtnTest_Click(
object sender, EventArgs e)


{


TxtName.Text = "George";


}


When I run my application and do a Left
-
Mouse
-
Click on the “Test” Button, a “Left
-
Mouse
-
Click” event is
generated and it sends a
message to the Windows OS to let it know that a user
clicked

the Left
-
Mouse
-
Button
on the “Test” Button component. The Windows OS then looks at this message (event), determining that it
came from my application and sends
this

message to my applications me
ssage queue. My application
,

when it
gets around to it
,

examines the message (event) and calls the
BtnTest_Click

method passing it two
parameters 1) sender and 2) e. The sender is my
BtnTest

upcast to an object reference and

e


is an
EventArgs object re
ference “
e
” that contains information about the mouse click event. Our method now sets
the
TxtName.Text

property to the string literal “
George
” which is displayed in that TextBox. Our Form now
waits for
the next

event.

private void TxtName_KeyPress(objec
t sender, KeyPressEventArgs e)


{


if (e.KeyChar == (char)Keys.Enter)


{


MessageBox.Show(TxtName.Text, "Enter Key Press");


}

}


Now

click on the
TxtName

TextBox and open the
Properties Window. When you click on the Shazam
Figure
12

TextBox Keypress Event

284

Chapter 15 Types of Classes in C#



(
lightning

bolt
)
, this opens the list of event

handlers for our TextBox, there are quit
e

a few
events as you can
see
, now double click on the “
KeyPress
” event. By
doing this the IDE generates an event handler called

TxtName_KeyPress


and also writes the event handling method shown above.


I wrote the code, in the
KeyPress
event method, that looks at the “
KeyPressEventArgs


object “
e
” and looks
for the “
Keys.Enter
” key to be pressed, when it
is,

it brings up the MessageBox and displays the text in our
TextBox.

However, this KeyPress event works similar to the mouse click event discussed earlier. When we
click in the TxtName TextBox, this gives focus to
the

TxtName

TextBox
, which associates
all
KeyPress events
with this TextBox. When a key is pressed this event sends a message to the Windows OS which tells
the OS,
what key was pressed, that it was pressed and some other information. The Windows OS sees that
this ev
ent
was

from our application and places it in the event (message) queue for our application. When our
application gets around to it, it takes the message (event) from the queue and sends it to our
TxtName_KeyPress event handling method. The code I wrote l
ooks at the key to see if it is an “
Enter
” key and
if it is not it returns; however, if it is it displays the MessageBox.


14.1.1 Form

There are two ways to exit our application and close the Form. The first is by calling the static class
“Application” Ex
it method or the Forms Close method as shown in the code snippets below


Application
.Exit
();

Close( ); or this.Close( );


Our GUI Application consists of a Form and a number of associated controls on the Forms Client surface. The
Form has a number of
properties and events. The properties and events we are initially interested in are



Properties:



Name


The reference to the Form object



Text


The text displayed on the Form’s Title Bar


Events:



Left
-
Mouse
-
Click



KeyPress


14.
1.1 Button

A Button

control

is used mainly to accept Button click events and respond to them in some way.
There are various Buttons that we can use in our GUI application. These include:



Button


RadioButton


ToolStripButton


Button

The code snippets illustrate how to set
or get various Button properties.



Properties:



B
tnTest.Text = “Exit”;



BtnTest.BackColor = Color.
PowerBlue
;



BtnTest.ForeColor = Color.Red;



string stg = BtnTest.Text;



285




Events:

Left
-
Mouse
-
Click

Right
-
Mouse
-
Click


RadioButton

A RadioButton is
design
ed

to be used with two or more RadioButtons in a group. When on
RadioButton is clicked (Checked=true) the other RadioButtons in the group will be unchecked
(Checked=false).
This concept originated from the old mechanical radio buttons, so when you
pushed one button in it forced all the other buttons out, thus only one button (radio station) at a
time could be selected.
The following are some properties of RadioButtons.



Properties:

RBtnSalary.Text = “Salary Employee”;



RBtnSalary.Checked = “true”;



bool btnChecked = RBtnSalary.Checked;



RBtnSalary.ForeColor = Color.Green;



Events
:


Mouse
Clicked


ToolStrip Buttons

The use of ToolStrips are beyond the scope of this chapter. You can investigate their use in the
Visual Studio Help.


14.
1.2

TextBox

A TextBox can either display (store) text strings or we can copy the text string. The main event
used by the TextBox is the KeyPress event and the mouse click event. There various forms of
TextBoxes. These include:



TextBox


RichTextBox


ListBo
x


ComboBox


TextBox

The TextBox control or component is used to display text or enter text from the Keyboard. The
following code snippets illustrate how to use its properties and events.



Properties:

T
xtName.Text = “Hello world”;



string stg =
TxtName.Text;



TxtName.BackColor = Color.Aqua;



TxtName.ForeColor = Color.Red;



TxtName.Enabled = false;

286

Chapter 15 Types of Classes in C#





TxtName.Visible = false;



TxtName.ReadOnly = true;



TxtName.TextAlign = HorizontalAlignment.Center;



Events
:

Mouse



Click, KeyPress


RichTextBox

A
RichTextBox control
,

is a combination of a multiline visual display panel and a
backing array of
strings. What
ever is placed in the display panel is stored in the backing array and whatever is
stored in the backing array is displayed in the
visible panel. You add strings to the backing array
with the following code



R
TxtDisplay.AppendText(“Hello world!
\
r
\
n”
);


RTxtDisplay.Clear( );


int length = RTxtDisplay.Lines.Length;



ListBox

A ListBox
is a rather ridged relationship

between
the
backing store array and the displayed panel.
The following is the code that shows how to access its properties.


L
BoxList.Items.Clear( );

LBoxList.Items.Add(“Line O”);

string stg = (string)LBoxList.Items[0];

int count = LBoxList.Items.Count;


Events
-

Sel
ectedIndexChanged, KeyPress



ComboBox

The ComboBox is a combination of a TextBox, Dropdown ListBox and a Button. It has some unique
properties that make it a very useful control. The code snippets below show how to access some of
its properties.


C
BoxList.
Items.
Clear( );

CBoxList.SelectedIndex;

CBoxList.Items.Add(“One”);

s
tring stg = (string)CBoxList.Items[0];


Events


SelectedIndexChanged, KeyPress


14.1.3 Label

Labels are mainly used to display information to our user and “Label” things like TextBoxes, etc.
However, they have a Text property that can be set at design time, but modified at runtime. We can
287


get the Label’s Text property or set it. Labels can also
respond to mouse clicks and other such
events.


Properties
:

Name,
Text, Font, Size, Shape, Color, etc.


Events: Mouse
-
Click



14.
4
.1
Putting It All Together


Fig. 13 is an example of a more complex design of a GUI interface it has a MenuStrip with two menu

items
“Exit” and “File” these menu items have two submenus as shown in Fig. 14.



Also included on the Client design
surface is a Label


Name, TextBox


George Washington as text and it is
ReadOnly, ComboBox


Butter
displayed (dropdown shown in Fig.
?)
, RichTextBox


Selected Index: 1
displayed, ListBox


Line 0, Line 1,
etc. displayed, two RadioButtons


Salary Employee and Hourly
Employee and three Buttons


Test,
Exit and Clear All.

The complete Windows Forms
Application is on the course Website.



Figure
13

A More Complex GUI Design


The MenuStrip provides the ability to have main menus such as
Exit and File and submenus like Load and Save. You can add these
to the MenuStrip at design time. By double
-
clicking on the Load
or Save submenus the IDE will generate a
n event handler for
these submenus.



Figure
14

Dropdown Menu for File

288

Chapter 15 Types of Classes in C#




Figure
15

Dropdown Menu for Exit

The Exit dropdown submenu displays the Exit and About subm
enus and by double
-
clicking on
these the IDE will also generate event handlers where we can write the code necessary to provide
the service requested by these events. In this application the Exit event will close the Form and
Application and the About eve
nt will display a MessageBox.


The ComboBox is a combination of three controls; 1)
Button, TextBox and a dropdown ListBox, as shown in
Fig. 16. When you left
-
mouse
-
click o
n the Button (blue
button with down arrow) it drops the ListBox as shown
in the Figure. When you left
-
mouse
-
click on the “Butter”
list item it will display that text in the TextBox and also
generate a “SelectedIndexChanged” event. Each item in
the ListBo
x is index
ed

in an array of strings from “0
Bread,”


1 Butter,” “2 Eggs,” and “3 Bacon.”

This application has been programmed to response to
various mouse
-
clicks and
key press

events to display
information in the TextBox, RichTextBox and ListBox. It
also sets the TextBox to ReadOnly and also sets its Visible property to false. The Test Button has its
BackColor and ForeColor to those shown in Fig. 13. You need to obtain the pr
ogram from the
course Website and play with it to increase your knowledge of the GUI design techniques. Have fun!

Figure
16

The ComboBoxes Dropdown ListBox