cse2207/cse3007 rapid applications programming with windows week 5

50
CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Upload: sophie-brooks

Post on 31-Dec-2015

222 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

CSE2207/CSE3007Rapid Applications

Programming with Windows

Week 5

Page 2: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Topics Week 5

Dialog BoxMenusWorking with MDIMore controlsValidation

Page 3: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Dialog Boxes

The CommonDialog custom control provides a standard set of Windows dialog boxes for File Open, Save, Print and selecting Fonts and Colors. Add it to the Toolbox via Project|Components|Controls Tab

Properties vary according to dialog type DialogTitle DefaultExt Filter Flags CancelError Filename

Page 4: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Dialog Boxes...

Methods ShowOpen ShowSave ShowFont ShowPrinter ShowColor

At design time, place ONE CommonDialog on the form

At run-time, set properties, then use method to display various types

DialogBox Type Principal PropertiesOpen FileNameSave As FileNameColor ColorFont FontName, FontSize, FontBold

Page 5: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Dialog Boxes… Examples

Private Sub cmdOpen_Click()cdlCommon.Filter =

“Text Files|*.txt|FRM Files|*.frm|All Files|*.*”cdlCommon.filename = “”cdlCommon.ShowOpen

End SubPrivate Sub cmdSave_Click()

cdlCommon.Filter = “TextFiles|*.txt”cdlCommon.DefaultExt = “TXT”cdlCommon.InitDir = “C:\MYVB\APPS”cdlCommon.ShowSave: End Sub

Page 6: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Menus

Start Menu Editor from Tools or ToolbarUse to create menu titles, menu items,

sub-menu titles, submenu itemsClick OK to close Menu Editor, then Menu

appears in design view of current formTo write code for a menu title, open any

code window, navigate to the menu title via the Object Box

To write code for a menu item click it to open its Code window

Page 7: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Menus...

Features separator bars to group related items Access keys for Menu titles, Menu items Shortcut keys for Menu Items Disable items not currently applicable e.g.

“Save” Make menu items invisible until required Indicate which menu item is currently active

and then remove the check mark e.g.[frmStart.]mnuChoicesView.Checked = True

Page 8: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Menus...

Private Sub mnuEdit_Click()If txtEdit.SelText = “” Then ‘ If no text selected

mnuEditCut.Enabled = FalsemnuEditCopy.Enabled = False

Else ‘ text is selectedmnuEditCut.Enabled = TruemnuEditCopy.Enabled = True

End IfEnd Sub

Page 9: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Menus...

Pop-Up Menu display anywhere on the form - usually near

the control it is providing menu options for usually invoked by clicking the right mouse

button create pop-up menu in the Menu Editor and

Clear the Visible checkbox write code as required by locating pop-up

menu controls in the Object Box of the Code Editor

Page 10: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Menus...

Pop-Up Menus Contd.… must have at least one submenu display via PopupMenu method

object.PopupMenu menuname, flags, x, y, boldcommand flags specifiy location and behaviour e.g.vbPopupMenuLeft/Center/Right Align (0, 4, 8)vbPopupMenuLeftButton (0) ‘ default item behaviourvbPopupMenuRightButton (2) Code following PopupMenu method call is suspended until

menu choices are completed.

Page 11: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Menus...

A Pop-up Menu to Zoom in/out on an image controlPrivate Sub imgPicture_MouseDown(Button as Integer….))

If Button = 2 ThenMe.PopupMenu mnuPopup,

vbPopupMenuRightButton Or vbPopupMenuCenterAlignEnd If Private Sub mnuZoomIn_Click()

Screen.ActiveForm.ActiveControl.Width = Screen.ActiveForm.ActiveControl.Width * 2 ‘/ 2 for zoom out

Screen.ActiveForm.ActiveControl.Height =Screen.ActiveForm.ActiveControl.Height * 2 ‘/ 2 for zoom out

End Sub

Page 12: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Multiple-Document Interface

One MDI parent window (a form) is a container for 1-> many MDI child windows (other forms) Each child form has its MDIChild property = True Child windows always display within the parent Minimized child form icon displays on the parent If parent is minimized, all the open child forms AND

the parent form are represented by a single icon The caption of a maximized child form displays on

the parent form title bar, combined with the MDI parent form caption

Page 13: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Multiple-Document Interface...

MDI is useful for applications where you need to view and work with more than one window at a time, which share a common menu, status bar etc document processing image viewing

Child windows may be all the same ‘type’ e.g. travel booking forms, or may be related parts of a large task e.g. creating an invoice

Page 14: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Multiple-Document Interface...

Create an MDI parent form (only 1 per application) from Project|Add MDI Form Parent, child forms may not be modal Can contain only Menu objects, picture boxes, or a

custom control such as SSPanel, with an Align property Can place other controls in picture box, panel Controls placed on parent are aligned Top, Bottom,

(take up full Width of form). And aligned Left, Right (take up full height of form)

Your application can also include standard, non-MDI forms that are not contained in the MDI form.

Page 15: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Multiple-Document Interface...

At design time, create an MDI child form by creating a new form and setting its MDIChild property to True. VB uses special icons in the Project Window to identify MDI forms

At run-time: If an MDI child form is the startup form, the MDI parent form is

loaded automatically If an MDI parent form is the startup form,

child forms can be explicitly loaded e.g. Load frmChild ‘default auto show of child form nowUse AutoShowChildren property (True/False)

special icons in the Project window for the MDI and MDI child forms.

Page 16: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Multiple-Document Interface...

At Run-Time:MDI parent form displays menu from currently

active child form (if any) or its own menuUse the MDI parent menu to show

controls/menu that are always neededUse the Child menu to show controls/menu

specific to the child formOR, use just the MDI parent menu, with

options disabled depending on which child form is active.

Page 17: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Multiple-Document Interface...

If MDI child forms have identical functionality, create one child form at design time, then at run-time, create a new instance of the child form when required via code e.g. to open a new travel booking form, display another image etc

New Document/Image/Form menu option The child form created at design time becomes

the ‘template’ for child forms created at run-time they inherit name, controls and properties they share the same events code

Page 18: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

MDI Code Example

This procedure creates and then displays a new instance (or copy) of Form1, called NewDoc. Each time the user chooses New from the File menu, an exact duplicate (instance) of Form1 is created, including all the controls and code that it contains.

Private Sub mnuFileNew_Click ()' Create a new instance of Form1, called NewDoc.Dim frmNewDoc As New Form1' Display the new form.frmNewDoc.ShowEnd Sub

Page 19: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

MDI Code Example

The code for the Form_Resize event procedure, like all the code for Form1, is shared by each instance of Form1.

Private Sub Form_Resize ()' Expand the text box on the current child form to

fill the current child form's internal area.Text1.Height = ScaleHeight ‘Don’t use form nameText1.Width = ScaleWidth ‘By default, applies to

currentEnd Sub ‘active form

Page 20: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Setting Child Form Size and Position

When an MDI child form has a sizable border (BorderStyle = 2), Windows determines its initial height, width, and position when it is loaded. The initial size and position of a child form with a sizable border depends on the size of the MDI form, not on the size of the child form at design time. When an MDI child form’s border is not sizable (BorderStyle = 0, 1, or 3), it is loaded using its design-time Height and Width properties.

If you set AutoShowChildren to False, you can change the position of the MDI child after you load it, but before you make it visible.

Page 21: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Working with MDI (Parent) Forms and Child Forms

When a user can open, save, and close several child forms in one session, you need code to identify the currently active form and control, and maintain state information on child forms.

Child forms may be ‘clones’ (created at run-time with the NEW statement) or created at design time with MDIChild property = True

Page 22: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Working with MDI (Parent) Forms and Child Forms...

ActiveForm property of MDIForm Object (parent) returns a reference to the currently active MDI child form

ActiveControl property returns the control with current focus

Private Sub EditCutProc () ‘ in MDIForm DeclarationsIf TypeOf ActiveForm.ActiveControl Is TextBox ThenClipBoard.SetText ' Copy selected text[frmMDI.]ActiveForm.ActiveControl.SelText[frmMDI.]ActiveForm.ActiveControl.SelText = “”End If: End Sub

Page 23: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Working with MDI (Parent) Forms and Child Forms...

When a user quits an MDI application, check that there is no unsaved data on any of the child forms. Declare a Public Boolean variable on each child

form.Public blSaved As Boolean ‘Scope of public form

variable ‘ is whole applicationPrivate Sub Text1_Change () ‘Whenever data is changed: blSaved = False End Sub

When data is saved (e.g. via File|Save code), reset:blSaved = True

Page 24: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Working with MDI (Parent) Forms and Child Forms...

User may Exit the application in various ways, so: Explicitly unload the MDI parent form, to invoke

the QueryUnload event for parent and each child Code for QueryUnload event can cancel the

unload for all forms QueryUnload event occurs in all forms before

any are unloaded. Unload event occurs as each form is unloaded

cancel argument: set it to any non-zero value to stop the QueryUnload event in all loaded forms, and so stop the form and application from closing

Page 25: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Working with MDI (Parent) Forms and Child Forms...

Private Sub mnuFileExit_Click()' When the user chooses File|Exit in an MDI application,

unload the MDI form to invoke the QueryUnload event for MDI parent and every open child.

Unload frmMDIEnd Sub

__________________________________Private Sub Form_QueryUnload(Cancel As Integer,

UnloadMode As Integer)

Dim strMsg As String, strFilename As String, strNL As String

Dim intResponse As Integer

Page 26: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Working with MDI (Parent) Forms and Child Forms...

If blSaved = False ThenstrFilename = Me.Caption‘Me references current form strNL = Chr(10) & Chr(13)strMsg = "The text in [" & strFilename & "] has changed."strMsg = strMsg & strNLstrMsg = strMsg & "Do you want to save the changes?"intResponse = MsgBox(strMsg, vbYesNoCancel,

frmMDI.Caption)Select Case intResponseCase 2Cancel = True ' User chooses Cancel; don’t unload form

Page 27: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Working with MDI (Parent) Forms and Child Forms...

Case 6 ‘ User chooses Yes; save the child form.strFilename = InputBox(“Save File As?”, “Save”,

strFilename) ' Get the filename to save file, or use default

If strFilename = "" Then ' If no filename,Cancel = True ' cancel the unload; otherwise, save it.ElseSaveFileAs (strFilename) ‘See Example 4End IfCase 7 ' User chooses not to save, so unload the formCancel = TrueEnd SelectEnd If: End Sub

Page 28: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Working with MDI (Parent) Forms and Child Forms...

Most MDI applications provide a Window menu. Displays the captions of all open child forms. Can manipulate the child windows display such as

Cascade, Tile, and Arrange Icons. Any ONE menu control on an MDI form or MDI child

form can be used to display the list of open child forms by setting the WindowList property for that menu control to True. At run time, Visual Basic automatically manages and displays the list of captions and displays a check mark next to the one that had the focus most recently. In addition, a separator bar is automatically placed above the list of windows.

Page 29: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Working with MDI (Parent) Forms and Child Forms...Private Sub mnuCascade_Click () ‘Cascade child

formsfrmMDI.Arrange vbCascadeEnd SubPrivate Sub mnuTile_Click ()' Tile child forms (horizontal).frmMDI.Arrange vbTileHorizontalEnd SubPrivate Sub mnuArrangeIcons_Click ()' Arrange all child form icons.frmMDI.Arrange vbArrangeIconsEnd Sub

Page 30: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

The Unload Event

Occurs just before a form is removed from screen (and memory). Triggered by: clicking the windows Close button by using the Unload statement in code

Perform form ‘clean-up’ code, or cancel the unload

Private Sub Form_Unload(Cancel as Integer)Const conBtns As Integer = vbYesNo + vbExclamation + vbDefaultButton1 + vbApplicationModalDim intUserResponse As IntegerintUserResponse = MsgBox(“Exit Now?”, conBtns, “Stock”)If intUserResponse = vbNo Then

Cancel = 1End If: End Sub

X

Page 31: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

More ControlsProject|Components|Controls|Microsoft

Windows Common Controls 6.0, …Controls-2 6.0, and ….Controls-3 6.0

Timer control (intrinsic) Once started, executes as background task Stop or suspend by setting Enabled to False,

or Interval to 0 Resume by setting Enabled to True More accurate than a loop for e.g pausing Triggers a Timer Event when preset Interval

has elapsed: write code for the event Works independently of the user

Page 32: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

More Controls...VScrollBar, HScrollBar, FlatScrollBar,

Slider navigate a list of options, a long document visual representation of integer value or position user input device for e.g. speed, volume Properties: Value (0-32,767), Max and Min.

LargeChange and SmallChange (not the Slider) Change event triggered by user moving Scroll

Box/Slider

ProgressBar Control Write code to modify the Value property, thus

displaying the progress of time-consuming tasks e.g. loading, saving a file. See Code Example 1

Page 33: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

More Controls...

UpDown Control Properties: BuddyControl, BuddyProperty, SyncBuddy Use with e.g. a Text Box, Command Button (not Label) Set Min, Max, Increment, Wrap properties

DTPicker, MonthView controls also in .OCX UpDown property True provides UpDown control instead

of a dropdown MonthView control Format property allows e.g. Long Date, Time, Custom Also Year, Month, Day, MinDate, MaxDate properties In Form Load: DTPicker1.Value = Now See Example 2

Page 34: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

List Boxes, Combo Boxes

Allow user to choose one (or more) options from a list of options

Help to ensure that only valid data enters the application

Flexible display format adapts for optimum interface design

Default selection speeds data inputProvide keyboard access via a Label

control, with TabIndex set to 1 less than that of List/Combo

Page 35: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

List Boxes, Combo Boxes...

List BoxSize list box to best fit the interfaceDisplay 3 -> 8 selections (recommended)VB automatically provides scroll-bars to access

non-visible entries & multiple columns (Columns)MultiSelect property returns (at run-time) or sets

(at design time) an integer value 0 No multiple selection allowed (Default) 1 Simple multiple selection (mouse click or spacebar) 2 Shift+click or arrow key, Ctrl+click or arrow key

Page 36: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

List Boxes, Combo Boxes...

To process multiple selections in a List Box:

Private Sub cmdPrintChoices_Click()Dim intSize as Integer, intCount as IntegerintSize = lstStates.ListCount - 1For intCount = 0 to intSize Step 1

If lstStates.Selected(intCount) = True ThenPrint lstStates.List(intCount)

End IfNext

End Sub

Page 37: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

List Boxes, Combo Boxes...

Combo BoxCombines features of a List Box + Text BoxStyle property specifies look and behaviour

0 DropDown Combo. User can select from list or type new entry (default). Uses least space.

1 Simple Combo. Text Box + list (NOT drop-down). Resize during design, set Height at run-time

2 DropDown List - Text box entry not available - use to restrict user to list of available options.

Page 38: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

List Boxes, Combo Boxes...Common Properties

ListCount: Number of list items. Always 1 more than largest index value

ListIndex: Position of the currently selected item in the control’s List property array (begins with 0)e.g. set 1st item as default: lstStates.ListIndex =

0**Careful! This automatically triggers the Click

event!!in multiple selections, ListIndex holds the index

of the item which has current focus (not necessarily selected)

-1 if nothing currently selected, or if user has typed into a Combo

Page 39: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

List Boxes, Combo Boxes...

Common Properties contd.… Text: Stores currently selected list item (or value

typed by user into Combo text box) NewIndex: Index of most recently added list item List: String array containing every item in the list

Allows access to every item in the list e.g.For intCount = 0 to (lstStates.ListCount - 1)

lstStates.List(intCount) = “****”Next ‘ items must already exist

ItemData: Array of Long data type. Used to store numeric values associated with the displayed string items in the List array e.g. lstEmployees.ItemData(0) = 123456

Page 40: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

List Boxes, Combo Boxes...

Common Properties contd.... Sorted: List items are auto-sorted if True. New items

are added in sorted order. (Sort is NOT case-sensitive)

Common Methods AddItem: Adds a string item to the list

lstEmploy.AddItem “Homer Simpson”lstEmploy.ItemData(lstEmploy.NewIndex) = 2222

RemoveItem: Removes specified item from listlstStates.RemoveItem 3 ‘ numeric index of

item Clear: Removes all items from the list

Page 41: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

SSTab ControlProject|Components|Controls, check Microsoft

Tabbed Dialog Control (SSTab Control)Allows display of multiple tabs on the same

area of window/screenEach Tab is a container for other controlsOnly one tab is active at any point (Index

from 0)Tab1.Tab = 1 ‘ 2nd tab is now active SSTab1.Caption = "Change"

At design time, select each tab in turn, then place controls, set tab properties (caption, accelerator key, picture, style, tabs per row)

Page 42: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Other Useful ControlsToolBar, CoolBar

Try the ToolBar Wizard!Status Bar

Contains regions called Panels ImageList: Repository for graphic filesTree-View, List-ViewChart Rich Text BoxMS FlexGrid ImageCombo

Page 43: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Data Entry, Validation, SetFocus method allows you to move the focus

to a specified control or form while the application is running and the form is visible If used in the Form_Load() event, must code

Form.Show() first. Control to receive focus must be enabled User input is then directed to that control

GotFocus event triggered by user action (tab, click) or code use to e.g. display ‘help’, change control

color

Page 44: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Data Entry, Validation...LostFocus event

triggered when object loses focus use to reverse GotFocus actions, validation

Private Sub Text1_LostFocus() If UCase(Text1.Text) <> "Y" Then MsgBox "Error!" Text1.SelStart = 0 Text1.SelLength = Len(Text1.Text)

Text1.SetFocus End IfEnd Sub

Page 45: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

The Validate Event, CausesValidation Property

Private Sub Form_Load()'Set button's CausesValidation property to False. When

the user clicks the button, the Validate event does not occur.

'Set the Caption of the button to "Help". With Command1 .CausesValidation = False .Caption = "Help" End With Show ‘by default applies to current form module

With Text1 'Select text and set focus .SelLength = Len(Text1.Text)

.SetFocus ‘Form must be visible End With: End Sub

Page 46: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

The Validate Event, CausesValidation Property...Both Text1 and Text2 have their CausesValidation

property set to TruePrivate Sub Command1_Click()'Give the user help when ‘Help’ button is clicked. (Validate

events will not fire) MsgBox "Text1 must be set to a date." & VbCrLF & "Text2

must be a number less than 10.” : End SubPrivate Sub Text1_Validate(KeepFocus As Boolean)'If the value is not a date, keep the focus, unless the user

clicks HelpIf Not IsDate(Text1.Text) Then

KeepFocus = True MsgBox "Please insert a date in this field.", , "Text1” : End

If : End Sub

Page 47: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

The Validate Event, CausesValidation Property...

Private Sub Text2_Validate(KeepFocus As Boolean)

' If the value is a number larger than 10, keep the focus.

If Not IsNumeric(Text2.Text) Or Val(Text2.Text) > 10 Then

KeepFocus = TrueMsgBox "Please insert a number less than or

equal to 10.", , "Text2" End IfEnd Sub

Page 48: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Data Entry, Validation...

Event Procedure which allows the user to press only numbers 0 to 9, and the Backspace key. Any other key pressed is cancelled

Private Sub Text2_KeyPress(KeyAscii As Integer) If (KeyAscii < 48 Or KeyAscii > 57) And _ KeyAscii <> 8 Then KeyAscii = 0 End IfEnd Sub

Page 49: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

Data Entry, Validation...

Event procedure which allows user to type a new entry into the TextBox portion of a Combo Box, and then have the new entry added to the list

Private Sub cboUsers_KeyPress(KeyAscii As Integer)If KeyAscii = 13 Then ‘ If ENTER is pressedIf cboUsers.ListIndex = -1 Then ‘ entry is not in listIf MsgBox(Want to Add “ & cboUsers.Text & “?”, vbYesNo + vbQuestion, “No Such User!”) = vbYes ThencboUsers.AddItem cboUsers.TextEnd If: End If: End If

End Sub

Page 50: CSE2207/CSE3007 Rapid Applications Programming with Windows Week 5

‘Automatic’ Events... Text1.Text = “Hello” ‘ triggers Text Box Change

eventWatch for ‘cascading’ Change event procedures e.g.

user changes a value, then your code increases it by x%Private Sub Text1_Change() Text1.Text = ”Try This!”End Sub In VB it is possible to trigger any event procedure

from any other event procedure- use with care!! If the same block of code is needed from two different

places in your application, write a form or application-level procedure, and pass it relevant arguments