Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Lect Note On Chapter 3 - Part I - Event-Driven Component

Uploaded by

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

Lect Note On Chapter 3 - Part I - Event-Driven Component

Uploaded by

beshahashenafi32
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Basic GUI

Objectives
• To understand the design principles of graphical user interfaces
(GUI).
• To understand, use and create events.
• To understand the namespaces containing GUI components
and event-handling classes and interfaces.
• To be able to create graphical user interfaces.
• To be able to create and manipulate buttons, labels, lists,
textboxes and panels.
• To be able to use mouse and keyboard events
Introduction
• A graphical user interface (GUI) allows users to
interact with a program visually.
• GUI gives a distinctive look, feel, and
consistent set of intuitive user-interface
components.
– E.g. GUI – browsers (chrom, firefox), windows
explorer, etc.
• Contain – menu and Set of buttons.
• Menu bar contain menus, set of buttons (toolbars), Labels –
caption/ indicate purpose, Scrollbars, etc.
• The menus, buttons, textboxes, labels and scrollbars are part of
GUI.
• They form a user-friendly interface through which the user
interacts with the program.
• GUIs are built from GUI components (also called controls or
widgets - short for window gadgets).
• A GUI component is an object with which the user interacts via
the mouse or keyboard.
Common GUI components
Windows Form
• Windows Forms (also called WinForms) create GUIs for
programs. It is a graphical element that appears on the
desktop.
• Type of form - dialog, window or MDI window (multiple
document interface window)
• A Component is a class that implements the IComponent
interface
• IComponent - defines the behaviors that components must
implement.
• Components are with or without graphical part
• component with a graphical part - control such as a button or
label. These are visible.
• Component that lack graphical part – are not visible (see next
slide)
Windows Forms controls and components contained in the Visual Studio .NET
Toolbox.

Component without graphical part

Component with graphical part


• When interacting with windows, we say that the
active window has the focus.
• The active window is the frontmost window and has
a highlighted title bar.
• A window becomes the active window when the user
clicks somewhere inside it.
– When a window has focus, the operating system directs
user input from the keyboard and mouse to that
application.
• The form acts as a container for components and
controls.
• Controls must be added to the form using code.
• Dragging a control from Toolbox onto the form
– generate code for us (instantiates control and sets control’s
basic properties).
• It is much easier to create and modify controls using
the Toolbox and Properties window, letting Visual
Studio .NET handle the details. This is known as visual
programming
• When the user interacts with a control by using the
mouse or keyboard
– events are generated, and
– event handlers process those events.
• Events typically cause something to happen in
response.
– E.g. clicking OK button in a MessageBox generates an
event.
• An event handler in class MessageBox closes the
MessageBox in response to this event.
• Each .NET Framework class (i.e., form, component and
control) is in namespace
– System.Windows.Forms
• Class Form (the basic window used by Windows
applications) is fully qualified as
– System.Windows.Forms.Form
• Likewise, class Button is fully qualified as
– System.Windows.Forms.Button
• General design process for creating Windows applications
requires:
– creating a Windows Form,
– setting its properties,
– adding controls, setting their properties and
– implementing the event handlers.
Common Form properties and events
• Visual Studio .NET generates most GUI-related code when we
create controls and event handlers.
• Programmers can use Visual Studio .NET to perform most of
these tasks graphically
– by dragging and dropping components onto the form and
– setting properties in the Properties window.
• In visual programming, the IDE generally maintains GUI-
related code, and the programmer writes the event handlers.
Event-Handling Mode
• GUIs are event driven (i.e. generate events when user
interacts with the GUI).
• Typical interactions that generate event include:
– moving the mouse, clicking the mouse, clicking a button,
typing in a textbox, selecting an item from a menu and
closing a window.
• Event handlers are methods that process events and
perform tasks.
– E.g. a form that changes color when a button is clicked.
• Note that clicking the button generates an event and
passes it to the event handler, and the event-handler
code changes the form’s color.
• Each control that can generate events has an associated
delegate that defines the signature for that control’s event
handlers.
• Delegates are objects that reference methods.
• Event delegates are multicast (class MulticastDelegate)—they
contain lists of method references.
• Each method must have the same signature (i.e., the same list
of parameters).
• In the event-handling model, delegates act as intermediaries
between objects that generate events and methods that
handle those events.
• Once an event is raised, every method that the delegate
references is called.
• Every method in the delegate must have the same signature,
because they are all passed the same information.

Event-handling mode
Basic Event Handling
• In most cases, we do not have to create our own events.
• Instead, we can handle the events generated by .NET controls
such as buttons and text boxes.
• These controls already have delegates for every event they
can raise.
• The programmer creates the event handler and registers it
with the delegate—Visual Studio .NET helps with this task.
– Example of windows application that displays a message box when
clicked.
• First, create a new Windows application.
• To register and define an event handler, click the Events icon in the form’s Properties window.
• This window allows the programmer to access, modify and create event handlers for a control.
• The dropdown button indicates that multiple handlers can be registered for one event.
• A brief description of the event appears on the bottom of the window.
• To create the event handler.
– Double-click the Click event in the Properties window
– This will create an empty event handler in the program code.
private void FormName_Click( object sender, System.EventArgs e )
{ //empty event handler generated, add some code to take action
}
• FormName_Click is a method called when the form is
clicked.
• For e.g we want a form display a message box.
– MessageBox.Show( "Form is pressed." );
• To do this, insert the statement in event handler to get
private void FormName_Click( object sender, System.EventArgs e )
{
MessageBox.Show( "Form is pressed" );
}
Description of an event handler

• Every event handler must have the signature that the


corresponding event delegate specifies.
• Event handlers are passed two object references.
– a reference to the object that raised the event (sender),
and
– a reference to an event arguments object (e).
• Argument e is of type EventArgs. Class EventArgs is
the base class for objects that contain event
information.
• The format of the event-handling method is:
void ControlName_EventName( object sender, EventArgs e )
{
event-handling code
}
• Where
– event handler name is by default the name of the control,
followed by an underscore (_) and the name of the event.
– have return type void and
– take two arguments—an object (usually sender) and an
instance of an event argument class.
• After creating the event handler, we must register it with
the delegate object, which contains a list of event handlers
to call.
• Registering an event handler with a delegate object
involves adding the event handler to the delegate’s
invocation list.
• Controls have a delegate reference for each of their events
—the delegate reference has the same name as the event.
– E.g. if we are handling event EventName for object myControl,
then the delegate reference is myControl.EventName.
• Visual Studio .NET registers events for us with code such
as the following from method InitializeComponent:
– this.Click += new System.EventHandler( this.MyForm_Click );
• The left-hand side is the delegate reference MyForm.Click. (this refers to
an object of class MyForm.)
• The delegate reference is initially empty—we must assign to it an object
reference (the right-hand side).
• We must create a new delegate object for each event handler.
• We create a new delegate object by writing
– new System.EventHandler( methodName ) ;
// returns a delegate object initialized with method methodName.
• The methodName is the name of the event handler, in our case it is
MyForm.MyForm_Click.
• The += operator adds an EventHandler delegate to the current
delegate’s invocation list.
• Since the delegate reference is initially empty, registering the first event
handler creates a delegate object.
• In general, to register an event handler:
– objectName.EventName += new System.EventHandler( MyEventHandler );
• More event handlers can be added using similar statements.
• Event multicasting is the ability to have multiple handlers for one event.
• Each event handler is called when the event occurs, but the order in which the
event handlers are called is indeterminate.
• Use the -= operator to remove the method from the delegate object.
Summary
• Information needed to register an event is
– EventArgs class (a parameter for the event handler) and
– EventHandler delegate (to register the event handler).
• This code is generated by Visual Studio .NET or type in by programmer.
– If Visual Studio .NET creates the code, the programmer does not have to deal with
going through all the steps, but the programmer also does not have complete control
of everything that is going on.
• For simple events and event handlers let Visual Studio .NET generate this
code.
• For more complicated solutions, registering your own event handlers might be
necessary.
Control Properties and Layout
• Controls derive from class Control (namespace System.Windows.Forms).
• Text property - specifies the text that appears on a control. It vary
depending on the context.
– E.g. the text of a Windows Form is its title bar, and the text of a button appears on
its face.
• The Focus method transfers the focus to a control. When the focus is on a
control, it becomes the active control.
• TabIndex property - determines the order in which controls are given
focus.
– automatically set by Visual Studio .NET, but can be changed by the programmer.
– helpful for the user who enters information in many different locations—the user
can enter information and quickly select the next control by pressing the Tab key.
• Enabled property - indicates whether the control can be used.
– Programs can set property Enabled to false when an option is unavailable to the
user.
• Visible property - without having to disable a control, the control can be
hidden from the user by setting the Visible property to false or by calling
method Hide.
Layout class - properties
• Visual Studio .NET allows the programmer to anchor and dock
controls, which help to specify the layout of controls inside a
container (such as a form).
• Anchoring - allows controls to stay a fixed distance from the
sides of the container, even when the control is resized.
• Docking - allows controls to extend themselves along the
sides of their containers.
– E.g. – if you want a control to appear in a certain position (top,
bottom, left or right) in a form even when that form is resized.
• specify this by anchoring the control to a side (top, bottom, left or right).
• In most cases, the parent container is a form; however, other
controls can act as a parent container.
Docking and anchoring demo
• The docking and anchoring options refer to the
parent container, which may or may not be the form.
• The minimum and maximum form sizes can be set
using properties MinimumSize and MaximumSize,
respectively.
– Both properties use the Size structure, which has
properties Height and Width, specifying the size of the
form.
• These properties allow you to design the GUI layout
for a given size range.
• To set a form to a fixed size, set its minimum and
maximum size to the same value.
Labels, TextBoxes and Buttons
• Labels provide text instructions or information about the
program.
• Labels are defined with class Label (derives from class Control).
– A Label displays read-only text/ can’t modified by user.
• A textbox (class TextBox) is an area in which text can be either
input by the user from the keyboard or displayed.
• A password textbox is a TextBox that hides what the user
entered.
• As the user types in characters, the password textbox displays
only a certain character (usually *).
• Altering the PasswordChar property of a textbox makes it a
password textbox.
• Deleting the value of PasswordChar in the Properties window
sets the textbox back to a regular textbox.
• A button is a control that the user clicks to trigger a specific
action.
– Other types of buttons, include checkboxes and radio buttons.
• All button types are derived from ButtonBase (namespace
System.Windows.Forms)  defines common button features.
• Button is often used to initiate a command.
• The text on the face of a Button is called a button label.
• Demo - create a program that uses a TextBox, a Button and a
Label.
• The user enters text into a password box and clicks the Button.
The text then appears in the Label. Normally, we would not
display this text—the purpose of password textboxes is to hide
the text being entered by the user from anyone who may be
looking over a person’s shoulder.
Common TextBox properties and events
GroupBoxes and Panels
• GroupBoxes and Panels arrange components on a GUI.
– E.g. buttons related to a particular task can be placed inside a
GroupBox or Panel inside the form designer.
• All buttons move together when the GroupBox or Panel is
moved.
• The main difference between the two classes is that
– GroupBoxes can display a caption, and Panels can have scrollbars.
– GroupBoxes have thin borders by default, but Panels can be set to
have borders by changing their BorderStyle property.
• These containers divides controls into functional “groups” that
can be arranged easily.
• To create a GroupBox – drag/ double click from toolbox
– Create new controls and place them inside the GroupBox, causing
them to become part of this class.
– These controls are added to the GroupBox’s Controls property.
– The GroupBox’s Text property determines its caption.
• To create a Panel – drag/ double click from tookbox
– To enable the scrollbars - set the Panel’s AutoScroll property to true.
– These scrollbars then can be used to view all the components in the
Panel (both when running and designing the form).
– This allows the programmer to see the GUI exactly as it appears to the
client.
Common properties of GroupBoxes and Panels
• The program in next slide uses a GroupBox and a Panel to
arrange buttons. These buttons change the text on a Label.
– The GroupBox (named mainGroupBox) has two buttons,
hiButton (labeled Hi) and byeButton (labeled Bye).
– The Panel (named mainPanel) has two buttons as well,
leftButton (labeled Far Left) and rightButton (labeled Far Right).
– The mainPanel control also has its AutoScroll property set to
True, allowing scrollbars to appear if needed (i.e., if the
contents of the Panel take up more space than the Panel itself).
– The Label (named messageLabel) is initially blank.
– The event handlers for the four buttons needed. To create an
empty Click event handler, double click the button in design
mode (instead of using the Events window). Add a line in each
handler to change the text of messageLabel.
CheckBoxes and RadioButtons
• They are types of state buttons
– can be in the on/off or true/false state.
• Classes CheckBox and RadioButton are derived from class
ButtonBase.
• A RadioButton is different from a CheckBox
– normally several RadioButtons grouped together, but only one of
the RadioButtons in the group can be selected (true) at any time.
• checkbox is a small white square - can be blank / contain a
checkmark. Checked or unchecked
• No restrictions on how checkboxes are used: Any number
may be selected at a time.
• checkbox label – is the text that appears alongside a
checkbox.
Common properties and events of class Checkbox appears
• The program that allows the user to select a CheckBox to
change the font style of a Label.
– One CheckBox applies a bold style, the other an italic style.
– If both checkboxes are selected, the style of the font is bold and italic.
• Change properties of control using the property window.
– Rename checkBox1 as boldCheckBox and set Text property to Bold.
– Rename checkBox2 as italicCheckBox and labele Italic.
– Rename label1 as outputLabel, and set the Text property Watch the
font style change.
• After creating the components, define their event handlers by
double clicking bold-CheckBox to create and registers an empty
CheckedChanged event handler.
• To change the font, the Font property must be set to a Font object.
– The Font constructor – take font name, size and style.
– Font name - is outputLabel.Font.Name (outputLabel’s Font object)
– Size – is output-Label.Font.Size
– style - is a member of the FontStyle enumeration (Regular, Bold, Italic,
Strikeout and Underline.
– A Font object’s Style property is set when the Font object is created
(which is read-only).
• Styles can be combined using bitwise operators, or operators that
perform manipulation on bits.
• Actions are taken and data are modified using these bit values.
• In this program, we need to set the font style so that the text will
appear bold if it was not bold originally, and vice versa
• The operand on the right (FontStyle.Bold) always has
bit values set to bold. The operand on the left, then
(outputLabel.Font.Style) must not be bold for the
resulting style to be bold.
• (Remember for XOR, if one value is set to 1, the other
must be 0, or the result will not be 1.)
• If outputLable.Font.Style is bold, then the resulting
style will not be bold. This operator also allows us to
combine the styles.
• For instance, if the text were originally italicized, it
would now be italicized and bold, rather than just
bold
private void italicCheckBox_CheckedChanged( object sender, System.EventArgs e )
{
outputLabel.Font = new Font( outputLabel.Font.Name,
outputLabel.Font.Size,
outputLabel.Font.Style ^ FontStyle.Italic );
}
Font family can be set new Font(new FontFamily("Times New Romans")
private void boldCheckBox_CheckedChanged( object sender, System.EventArgs e )
{
outputLabel.Font = new Font( outputLabel.Font.Name,
outputLabel.Font.Size,
outputLabel.Font.Style ^ FontStyle.Bold);
}
• Radio buttons (defined with class RadioButton) like
checkboxes - have two states—selected/ deselected.
• However, radio buttons normally appear as a group in
which only one radio button can be selected at a time.
• Selecting a different radio button in the group forces all
other radio buttons in the group to be deselected.
• Radio buttons represent a set of mutually exclusive options
(i.e., multiple options cannot be selected at the same
time).
• All radio buttons added to a form become part of the same
group.
• To create new groups, radio buttons must be added to
GroupBoxes or Panels.
Common properties and events of class RadioButton
• The program uses radio buttons to select the
options for a MessageBox.
• Users select the attributes they want then press
the display button, which causes the
MessageBox to appear.
• A Label in the lower-left corner shows the
result of the MessageBox (Yes, No, Cancel,
etc.).
• The different MessageBox icon and button
types have been displayed in tables in Chapter
5, Control Structures: Part 2.
• To store the user’s choice of options objects:
– iconType and buttonType are created and initialized.
• Object iconType is a MessageBoxIcon enumeration
– have values Asterisk, Error, Exclamation, Hand, Information,
Question, Stop and Warning.
• Object buttonType is a MessageBoxButton enumeration
– Have values AbortRetryIgnore, OK, OKCancel, RetryCancel,
YesNo and YesNoCancel.
• The name indicates which buttons will appear in the
MessageBox.
• In this example we use all MessageBoxButton
enumeration values.
• Two GroupBoxes are created, one for each enumeration.
• Their captions are Button Type and Icon. One label is the used to prompt the user
(promptLabel), while the other is used to display which button was pressed, once the
custom MessageBox has been displayed (displayLabel).
• There is also a button (displayButton) that displays the text Display.
• RadioButtons are created for the enumeration options, with their labels set
appropriately.
• The radio buttons are grouped, thus only one option can be selected from each GroupBox.
• For event handling, one event handler exists for all the radio buttons in groupBox1, and
another for all the radio buttons in groupBox2. Each radio button generates a
CheckedChanged event when clicked.
• Remember, to set the event handler for an event, use the events section of the Properties
window.
• Create a new CheckedChanged event handler for one of the radio buttons in
buttonTypeGroupBox and rename it buttonType_CheckedChanged.
• Then set the CheckedChanged event handlers for all the radio buttons in button-
TypeGroupBox to method buttonType_CheckedChanged.
• Create a second CheckedChanged event handler for a radio button in iconTypeGroupBox
and
• rename it iconType_CheckedChanged.
• Finally, set the CheckedChanged event handlers for the radio buttons in
iconTypeGroupBox to method iconType_CheckedChanged.
Menus and MDI…
• A PictureBox displays an image. The image can be one
of several formats, such as bitmap, PNG (Portable
Network Graphics), GIF (Graphics Interchange Format)
and JPEG (Joint Photographic Experts Group).
• A PictureBox’s Image property specifies the image
that’s displayed, and the SizeMode property indicates
how the image is displayed (Normal, StretchImage,
Autosize, CenterImage or Zoom).
• Figure 14.29 describes common PictureBox properties
and a common event.
private int ImageNumber { get; set; } = -1; // image to display
private void nextButton_Click(object sender, EventArgs e)
{
ImageNumber = (ImageNumber + 1) % 3; // cycles from 0 to 2
// retrieve image from resources and load into PictureBox
imagePictureBox.Image = (Image) (Properties.Resources.ResourceManager.GetObject(
$"image{ImageNumber}"));
@”C:\Users\Dag\Desktop\image1.jpg”

}
Using Resources Programmatically
• In this example, we added the images to the project as resources. This causes the IDE to to
copy the images into the app’s executable file and enables the app to access the images
through the project’s Properties namespace. When you do this, you don’t need to worry
about wrapping the images with the app when you move it to another location or computer.
• If you’re creating a new project, use the following steps to add images to the project as
resources:
• 1. After creating your project, right click the project’s Properties node in the Solution
Explorer and select Open to display the project’s properties.
• 2. From the tabs on the left, click the Resources tab.
• 3. At the top of the Resources tab, click the down arrow next to Add Resource and select Add
Existing File… to display the Add existing file to resources dialog.
• 4. Locate the image files you wish to add as resources and click the Open button. We
provided three sample images in the Images folder with this chapter’s examples.
• 5. Save your project.
• The files now appear in a folder named Resources in the Solution Explorer. We’ll use this
technique in most examples that use images going forward.
• A project’s resources are accessible to the app via its Resources class (of the project’s
Properties namespace). The Resources class contains a ResourceManager object for
interacting with the resources programmatically. To access an image, you can use the method
GetObject, which takes as an argument the resource name as it appears in the Resources tab
(e.g., "image0") and returns the resource as an Object.

You might also like