1 / 33

Visual Basic Programming II Lecture 2

Visual Basic Programming II Lecture 2. MIS 233 Instructor – Larry Langellier. This Week. Programming User Events – Chapter 12 Keyboard Events KeyPress, KeyDown, KeyUp, Clicking and Moving the Mouse MouseDown, MouseUp, MouseMove, Click, DblClick Dragging with the Mouse

Télécharger la présentation

Visual Basic Programming II Lecture 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Visual Basic Programming II Lecture 2 MIS 233 Instructor – Larry Langellier

  2. This Week • Programming User Events – Chapter 12 • Keyboard Events • KeyPress, KeyDown, KeyUp, • Clicking and Moving the Mouse • MouseDown, MouseUp, MouseMove, Click, DblClick • Dragging with the Mouse • Drag, DragOver, DragDrop • Introduction to Debugging – Chapter 13 • Types of Errors • Break Mode • Debugging Tools

  3. Capturing Key Presses • Users interact with Visual Basic programs using both the mouse and keyboard. We’ll focus on the keyboard first. • You should be familiar with shortcut keys in Windows applications – i.e. key combinations you can press to make a program action occur • The Menu Editor provides a simple mechanism for defining these shortcut keys that trigger menu options • What about other key presses you might want to define and capture? • When a user interacts with the keyboard, key events are generated • Visual Basic provides three event procedures for handling keyboard events • KeyPress • KeyDown and KeyUp

  4. Key Event Handlers • Available for most controls that you can type in – Text Box, Combo Box, etc. • KeyPress • occurs when a key corresponding to an ASCII character is pressed • Limited to 0-127 character set • One argument – KeyAscii • the ASCII value of the key pressed • KeyDown and KeyUp • occur as ANY key on the keyboard is pressed/released • Triggered by physical key press, you must interpret • Two arguments • KeyCode – a numeric code for the key • Shift – an integer informing whether Alt, Shift and/or Tab are pressed

  5. Key Event Handlers (cont.) • KeyCode constants vbKeyA – vbKeyZ vbKeyNumpad0 – vbKeyNumpad9 vbKeyF1 – vbKeyF16 vbKey0 – vbKey9 vbKeyDecimal vbKeyBack vbKeyTab vbKeyReturn vbKeyShift vbKeyControl vbKeyCapital vbKeyEscape vbKeySpace vbKeyInsert vbKeyDelete • Shift constants vbShiftMask vbAltMask vbCtrlMask • These are bit fields that can be added together to test for combos • Examples 12.1 – Using the Return Key 12.2 – Using a Function Key as a Menu Shortcut Key

  6. Which Should I Use? • Examples of situations KeyPress can’t handle • Arrow Keys • Page Up, Page Down • Numeric Keypad keys • Also, use KeyDown and KeyUp if you need to know if a key is held down

  7. Form KeyPreview Property • Key events work on the object with current focus – a Textbox, a ComboBox, etc. • A form can only have focus if it is blank or if all controls are disabled - this means the form can’t normally process key presses • Visual Basic provides you with a Form property that allows the form to capture all key events before they go to the control – the KeyPreview property • Syntax: frmMain.KeyPreview = True • KeyPreview is usually used when several controls need to respond the same way to key events • Key events will still pass to the control with focus for additional handling, unless we disable the handling mechanism by setting KeyAscii = 0 • Example: 12.14 – Digit filtering

  8. An Example Write a procedure that asks whether the user wants to exit the program when the Esc key is pressed. If the answer is yes, end the program; otherwise continue. Feel free to put any controls on your form that you’d like. The Esc key should be captured and processed regardless of what control currently has focus.

  9. Pseudocode If the Escape key is pressed Display a message asking the user if they want to quit If the user says yes Exit the application

  10. Sample Solution In the .frm file Private Sub Form_KeyPress(KeyAscii As Integer) Dim answer As Integer If KeyAscii = vbKeyEscape Then answer = MsgBox(" Are you sure you wish to exit?", _ vbYesNo, "Testing exit") Select Case answer Case vbYes End Case Else Exit Sub End Select End If End Sub

  11. Mouse Interaction • The mouse is used to: • Click buttons; • Move windows; • Resize windows, etc. • Visual Basic controls are capable of recognizing when the mouse: • is Single-clicked • is Double-clicked • is Moved • has a button Clicked • has a button Released • Like all other events you’ve seen in Visual Basic, you will need to write code to perform actions when the event is triggered

  12. Mouse Property - MousePointer • Before we look in more detail at how to handle Mouse Events, let’s look at a Mouse Property – MousePointer • Forms and Controls all have a MousePointer property • The MousePointer property doesn’t perform any action, it simply provides the user with visual feedback about what can be done with the mouse • MousePointer constants – Example 12.2a vbDefault vbArrow – select vbCrosshair – precision vbIbeam – text input vbSizePointer – resizing vbSizeNESW – NE to SW resizing vbSizeNS – N to S resizing vbSizeNWSE – NW to SE resizing vbSizeWE – W to E resize vbUpArrow – up arrow vbHourglass – busy waiting vbNoDrop – no drop allowed here vbSizeAll – resize all ways vbArrowQuestion – feature help vbCustom – design your own vbArrowHourglass –wait, but mouseable

  13. Mouse Events • When a user interacts with the mouse, mouse events are generated • Mouse Events: • Click – occurs when the mouse is clicked once • DblClick – occurs when the mouse is clicked twice quickly • MouseMove – occurs when the mouse pointer is moved • MouseUp – occurs when the user releases any mouse button • MouseDown – occurs when the user presses any mouse button • A form recognizes a mouse event when the point is over a part of the form with no controls. • Most controls recognize a mouse event when the pointer is over the control.

  14. Mouse Event Arguments • Handlers for Click and DblClick don’t have arguments • The arguments for MouseDown, MouseMove, and MouseUp are: • Button – refers to which button is pressed (left, right, middle) • Shift – refers to the state of the Shift, Alt and Ctrl keys • X and Y – refer to the coordinates of the mouse pointer relative to the form or control to which the mouse pointer is pointing • Examples • 12.3: Using the Image Move method with MouseDown • 12.3a: Demonstrating all 5 Mouse Events • 12.4: Using the MouseMove Event

  15. Mouse Buttons • The Button argument of MouseDown, MouseUp, and MouseMove indicates which mouse button was pressed • Button constants • vbLeftButton – Left Mouse button (= 1) • vbRightButton – Right Mouse button (= 2) • vbMiddleButton – Middle Mouse button (= 4) • MouseUp and MouseDown can only test for one button at a time • MouseMove can test more than one button • Combinations are tested by adding the values – 3 means right and left are pressed simultaneously • Examples • 12.5 – Coding a MouseUp Event • 12.5a – Graphical example of which mouse button is clicked • 12.6 – Coding a MouseMove Event

  16. Shift, Ctrl and Alt Keys • The status of the Shift, Ctrl and Alt keys can be determined when a MouseDown, MouseMove or MouseUp event occurs • A value representing the status of these keys is stored in the Shift argument • Shift constants • vbShiftMask – Shift key is pressed (= 1) • vbCtrlMask – Ctrl key is pressed (= 2) • vbAltMask – Alt key is pressed (= 4) • Combinations can be tested adding the values – 5 means the Shift and Alt keys are both pressed • Example – 12.7a • Notice the bit manipulation that determines if the Alt key is pressed a = Shift And vbAltMask • Bits are turned on and off corresponding to pressed or not pressed • And allows you to “mask off” to test a specific bit field

  17. Do It Together! Write a program that uses the mouse to draw a square on the form. The upper-left coordinate should be the location where the user first pressed the mouse button, and the lower-right coordinate should be the location where the user releases the mouse button.

  18. Sample Solution Option Explicit Dim mUpperX As Single Dim mUpperY As Single Private Sub Form_MouseDown(Button As Integer, Shift As Integer, _ X As Single, Y As Single) mUpperX = X mUpperY = Y End Sub Private Sub Form_MouseUp(Button As Integer, Shift As Integer, _ X As Single, Y As Single) Line (mUpperX, mUpperY)-(X, Y), , B Caption = "Area: " & (Abs(mUpperX - X) * Abs(mUpperY - Y)) & _ " Twips" End Sub

  19. Drag-and-Drop • A drag-and-drop operation consists of: • pressing and holding the left mouse button; • moving the mouse (the drag); and • releasing the mouse button (the drop) • Mouse and Key Events are not recognized while a drag-and-drop is in progress • Visual Basic provides two different ways to deal with Drag-and-Drop – manually and automatically • Drag-and-Drop events have a Source and Target • Source is the control being dragged • Target is the form or control over which the source is dragged or dropped

  20. Drag-and-Drop (cont.) • Source Control Properties • DragMode – enables automatic or manual dragging of an icon • DragIcon – identifies which icon is displayed when the control is dragged • Events (triggered on Targets) • DragDrop – recognizes when control is dropped onto an object • DragOver – recognizes when control is dragged over an object • The Drag Method (for manual dragging only) • Start or stop manual dragging (typically a Source event)

  21. DragOver Event • The Target Event is triggered when a Source moves over the Target • Syntax: cmdOK_DragOver(Source As Control, X As Single, _ Y As Single, State As Integer) • The Target in this example is cmdOK • State Argument Values • vbEnter – Source dragged into Target • vbLeave – Source dragged out of Target • vbOver – Source moved within Target • Example • 12.7: Coding a DragOver Event

  22. DragDrop Event • Target Event triggered when a Source control being dragged is dropped on a Target control by releasing the mouse button • Syntax: Image1_DragDrop(Source As Control, _ X As Single, Y As Single) • Example • 12.8: Coding a DragDrop Event • 12.11a: Dragging Buttons with Letters

  23. Drag Method • Allow more precise control over when you can drag a control • Set DragMode property to Manual (= 0) • Syntax: object.Drag action • Object is a control that can be dragged • Action specifies the action to be performed: • vbCancel – Cancel drag operation (= 0) • vbBeginDrag – Begin dragging Control (= 1) • vbEndDrag – Drop the Control (= 2) • Examples • 12.9: Using the Drag Method • 12.10a: Moving the Knight

  24. Just Do It! This is a slightly different “Just Do It!” problem. I’d like you to start working on homework problem 12.6 from Eliason and Malarkey. We won’t discuss the solution tonight, but I’d like you to get started on this before you leave to see if you have any further questions about Drag-and-Drop before you go. The problem states: “Use the TypeOf statement to test controls in a DragDrop( ) event. Add a picture box on the right-hand side of a form and a label, an option button, a check box, and an image on the left. Code a Drag-and Drop procedure using a TypeOf statement so that when a control from the left is dropped on the picture box, a message appears on the picture box identifying what type of control was dropped.”

  25. Debugging • Debugging is the Process of diagnosing and fixing errors in your code • Visual Basic provides an extensive collection of tools for debugging • Breakpoints • Stepping • Watch Window • Locals Window • Immediate Window • Call Stack

  26. Different Types of Programming Errors • Three Types – Syntax, Logic and Runtime • Syntax • Syntax errors can typically be prevented by choosing Tools->Options->Editor Tab->Auto Syntax check box • Color coding helps with syntax • Auto popups • Logic • Typically more difficult to find • Program may run but produce improper results • Debugging tools assist you by letting you “stop and watch” • Runtime • Attempt to execute an instruction that can not be carried out • Examples – divide by 0, Type mismatch

  27. Preventing Bugs • Always use Option Explicit to force variable declaration – this also helps eliminate misspelled variable names • Add comments while (or before) you write your code • Always use the syntax checker (Options -> Auto Syntax Check) • Use naming prefixes for variables (1st letter indicates scope, next three indicate the type of the object) • Use the tightest scope possible for variables and constants • Use the Private keyword to limit the scope of a procedure if it isn’t called outside the module • Perform range checking to insure values fall in the correct range, when possible • Check the validity of variable values before using them

  28. Debugging Strategies • Trace Debugging • Verify the flow of control in a program by using Print statements or MsgBox statements • At the beginning and end of a procedure • Prior to and after a loop • Check the value of important values along the way with Print statements also • Use the Debug.Print capability (discussed in a moment) • Examples Print “Entering procedure calcPaycheck” Print “Entering hour summation loop” Print “Total hours worked is “ & totalHours Print “Exiting hour summation loop” Print “Exiting procedure calcPaycheck”

  29. Break Mode • We’ve seen the design-time and runtime modes – now we’ll visit the Break Mode • In Break Mode, Visual Basic debugging tools are available • To make the Debug tool bar visible, choose View->Toolbars->Debug • There are two ways to enter Break Mode • Click on the Break button while a program is running to enter Break Mode • Control your entry into Break Mode with a Breakpoint • Clearing Breakpoints - Debug-> Clear All Breakpoints • Examples • 13.1: Setting a Breakpoint and Step Through a Procedure • 13.2: Stepping Over a Procedure • 13.3: Stepping Out of a Procedure

  30. Locals Window • Shows the values of all locally declared variables within a procedure being examined in Break Mode • Also allows you to change the values while in Break Mode • Example • 13.4: Using the Locals Window • Change the value of msg

  31. Watch Expressions • You can monitor the value of an expression or variable and break when the value changes or reaches a value you define • This allows you to avoid tedious repetitions and focus on a particular iteration that causes problems • Debug->Add Watch • Examples • 13.5: Adding a Watch Expression at Design-Time • 13.6: Setting a Break When Watch Expression Becomes True

  32. The Debug Object • Print Method • Values of expressions and variables can be displayed in the Immediate Window using Debug.Print • Example • 13.7: Using the Debug.Print Method in Code • Assert Method • Causes an entry into Break Mode when the value of an expression becomes false • Debug.Assert (CityName = “Portland”) • Example • 13.8: Using the Debug.Assert Method in Code • No Debug Object Methods are entered into a final compiled application

  33. Next Class… • Research Presentation Handout • Read Chapter 14 (Arrays) to prepare for next class • Homework #2 is due prior to the start of next class • Complete Chapter 2 (Mix and Match Cartoons) in the Programming Games with Microsoft Visual Basic 6.0 book. • No enhancements! • Do the following end of chapter Skill-Building Exercises in your textbook: • Chapter 12 - Exercises 2 and 6, Debug Exercise 4 • Complete Mini-Project #2 • E-mail the .vbp, .vbw, .frm, and .frx solution files to me • Don’t forget to keep up with your three weekly WebBoard postings/replies

More Related