8. winforms applicationscis.uws.ac.uk/mcmo-ci0/softdev/slides/chapter8.pdf · ¤programmer must...

22
8. WinForms Applications Writing native Windows programs

Upload: others

Post on 31-Oct-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

8. WinFormsApplications

Writing native Windows programs

Page 2: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Overview

n Windows Applicationsn Events and event handlersn Layered (tiered) model of softwaren Focusn Form designer and controlsn Dialog boxes and formsn Delegatesn Visual Inheritance

Page 3: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Windows vs Console appsn A console application has a very limited user-

interface¨ Keyboard for input¨ Console window (text only) for output

n Compared to this a Windows program provides a much richer range of interaction methods¨ On-screen buttons, scroll bars, lists etc.¨Multiple windows to categorize and simplify output

and inputn The penalty for this is a more complex

application structure

Page 4: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Windows and Eventsn Console programs follow

an InputàProcessàOutputmodel¨ Easy to program

n By contrast, a Windows program can have many different forms of input¨ Programmer must

orchestrate the various sources

n Each source of input fires ‘events’ the program must react to

Input Process Output

Software

Page 5: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Event handlersn Each source of events can kick off the execution

of a block of code called an event handler¨ An event handler is simply a Sub that is called

automatically by Windows in response to some external interactionn Typing into a text control etc.n ‘Clicking’ on a controln Selecting an item in a list

¨ Often, the event incorporates some additional information – which key was pressed, the exact location of the mouse cursor etc.n This information is passed in the form of parameters to the

event handler

Page 6: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Layers of softwaren Because of the wide range of stimuli (events) a program

has to react to, the structure of a Windows application is more complex

n One strategy for simplifying the structure is to try to keep application specific code and user-interface code separate¨ Application specific code is usually the set of classes that do the

actual job required of the program, often called the ‘business classes’

¨ User-interface code accepts user input and commands and directs the business classes according to these

n These two separate parts of a system can be thought of a ‘tiers’ or ‘layers’ in a system¨ User-interface tier comes between the user and the business tier

and is responsible for interpreting user interactions and effecting the appropriate changes in the business tier

Page 7: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

A 2-Tier Application

User-Interface Tier

Business Tier

Handles User Interactions

Implements Business Rules

Page 8: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

WinForms basics

n A Form is a top-level Window that is hosted and managed by the Windows operating system and which receives external interactions in the form of events

n Controls in Visual Basic are toolbox items that can be placed on a form to act as user-interface elements (or widgets)

n Windows considers a control to be another type of Window – a rectangular area of the screen that can receive the focus (explained later) and events

n This confuses the issue, and so the Visual Basic term ‘Control’ is a better description

Page 9: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

The Focusn The system mouse can, by virtue of its pointer, be used to

direct input to any visible window on a screen¨ The input is necessarily simple – movements, clicks, drags

n The keyboard is a richer form of input, but there is no natural way of directing its input

n To get over this, the Windows system registers which window has the current focus¨ In a text-oriented control, this is the cursor and acts as the

insertion point for typed characters from the keyboard¨ In other controls, the focus changes the control’s appearance

slightly to indicate which control is currently receiving keyboard events

¨ Focus can be changed using the Tab key on the keyboard¨ TheTabIndex of a control indicates its place in the tab order

Page 10: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Events and event handlersn Events can originate from¨ Forms or controls on forms¨ System hardware (e.g. the real-time clock)¨ Other windows programs

n Events are usually received by forms¨ Normal event-handlers are Subs on a form¨ Event-handlers can be coded into other modules, but

this involves more work¨ A form-based event handler is usually associated with

a specific event from a specific control¨ It has two parameters, indicating the object that sent

the event (sender) and an object containing related information (e)

Page 11: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Example event handlerPrivate Sub txtName_KeyPress(ByVal sender As Object, _

ByVal e As System.Windows.Forms.KeyPressEventArgs) _Handles txtName.KeyPress

Dim ch As Charch = e.KeyChar()e.Handled = True

End Sub

n The above handler is set to receive KeyPress events from a text box named txtName

n The sender parameter is simply a reference to this text boxn As a KeyPress event handler, you can rightly expect that

the other parameter will contain information on the key pressed – which key, whether Shift or Ctrl was pressed, etc.

Page 12: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Event lists

n A typical control can source a wide range of events under different circumstances

n Only events for which a handler is defined will have any effect

List of potential events from a TextBox control

Page 13: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

The Visual Studio form designern The Form-Designer performs a complex task –

synchronizing the graphical design of a form with the code¨ The actual ‘Form’ is a class that inherits from the Form

class. The graphical designer is simply a different view of it – a graphical class configuration panel

n As controls are added, properties changes and design wizards executed, the form code is updated to reflect the changes¨ Each control is a variable, and code to initialize it¨ Each property change is a statement that assigns a new

value to a property¨ A double click on a control generates a skeleton event

handler

Page 14: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Windows controlsn The standard WinForms toolbox contains a

wide range of controls. e.g.¨Text input: TextBox, RichTextBox, ComboBox¨Mouse input: CheckBox, OptionButton,

ListBox, ScrollBar¨Display and/or organize: Label, PictureBox,

Panel¨Command: Button, Menu, Timer

n All can be configured by the properties window or in code

Page 15: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Dialog boxesn A dialog box is a form that performs complete

operations¨ Buttons provided to confirm (usually OK) or cancel

(usually Cancel) the operation¨ Operation typically involves a number of data values,

which after editing them, the user selects OK or Canceln A VB Form has AcceptButton and CancelButton

properties that can refer to these buttons¨ This allows the DialogResult to reflect which button was

pressed – True for OK, False for Canceln A dialog box provides a Modal operation – while it

is in operation, the calling code has to wait for it¨ This imposes a level of control over the user (1 dialog at

a time)

Page 16: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Formsn A dialog box is a special type of formn More generally, any number of forms can be in

operation simultaneously¨ This can be a more difficult scenario to control

n Generally, use a single form to input and display the properties of an object and to initiate its methods

n A number of strategies can be taken to maintain control. e.g.¨ The object can ‘own’ (initiate, interrogate and dispose

of) a form and initiate its own display, update etc.¨ A form can ‘contain’ an object, and update and

display it (more suitable where one form is used to browse a collection of objects

Page 17: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Delegates and event handlersn A delegate is defined as a type of Sub

¨ A stand-in for real subs¨ Delegate defines name, parameters and return type, but does

not contain code

n The purpose of this is to be able to include a call to a sub in code before the sub has been written¨ Why would you do this? – think of what an event handler is

n Once a delegate type has been defined, a real sub can be assigned to it (just like a variable)¨ Then, a call to the delegate will be a call to the sub assigned to it¨ e.g.

¨ We can now assign a Sub (that matches AlarmCall) to AC

Delegate Sub AlarmCall(ByVal AlarmMessage As String)Dim AC As AlarmCall

Page 18: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Example of delegationClass AlarmClock

Private myTime As DatePrivate myMessage As String'Here is the delegate declaration...Private myResponse As AlarmCallPublic Sub New(ByVal AlarmTime As Date, _

ByVal Message As String, _ByVal SubToCall As AlarmCall)

myTime = AlarmTimemyMessage = Message'Assign a Sub to the delegate...myResponse = SubToCall

End SubPublic Sub Go()

DoIf TimeOfDay >= myTime Then

'A call to the delegate method...myResponse(myMessage)Exit Do

End IfLoop

End SubEnd Class

Using the delegate included here as a template, we can write a sub that will say what happens when an alarm goes off.

Page 19: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Example of delegation (contd.)'This one displays a message on screen...Sub AlarmMessageBox(ByVal aMessage As String)

MessageBox.Show(aMessage)End Sub'This one changes a form’s caption...Sub AlarmCaption(ByVal aMessage As String)

MainForm.Caption = aMessageEnd Sub'This one sends an email...Sub AlarmEmail(ByVal aMessage As String)

SendMail("[email protected]", "Alarm", aMessage)End Sub

Any of these three subs can be assigned to the delegate, and will be called when the alarm goes off. Note – all have same parameters as the delegate.

Sub Main()Dim AC As AlarmClock = _

New AlarmClock(TimeValue("10:00:00"),_ "Go to airport", AddressOf AlarmEmail)

AC.Go()End Sub

Page 20: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Visual Inheritance

n Code Inheritance allows a new class to be based on an existing class

n A Form is a class, designed in code like any other class (form designer just displays it in a more convenient form for us)

n Visual Inheritance allows us to take an initial form design (in a form builder window) and extend it by adding new controls

n As a result, the new form’s code will inherit from the existing one.

Page 21: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Visual Inheritance

Visual Inheritance

Form design and any code defined (including event handlers) for the original form is inherited by the new one.

Page 22: 8. WinForms Applicationscis.uws.ac.uk/mcmo-ci0/SoftDev/Slides/Chapter8.pdf · ¤Programmer must orchestrate the various sources nEach source of input fires ‘events’ the program

Summary

n Windows applications more complex than console ones, and so often a layered model is used to simplify

n Forms respond to events, and event handlers are written to define what happens when an event is received

n The Form designer allows controls to be placed on forms and configured with no program code

n Dialogs are special (modal) types of formn Delegates are used to pre-define a type of subroutinen Visual Inheritance allows a form design to be extended

within the form designer