Introduction to Programming Using Visual Basic by ygq15756


									  Introduction to Programming Using Visual Basic
               Lesson 10: Procedures

Hour 12: Procedures


A procedure is a block of statements that can take arguments, perform a series of
statements, and change the value of its arguments

Why Do We Need Procedures?

While quite a lot of programming can be done without procedures, they help in several
very important ways. First, they will save you programming time by allowing you to reuse
the same code over and over in your program. Second, they allow you to break up large or
complex tasks into understandable pieces. Third, they allow you to modularize your
program so that if the specifications of your program change, you can minimize the number
of lines that you must modify.

In the Abstract

The following example does not use Visual Basic statements. It is an abstract example to
introduce the concept of procedures. Later, we will use a more concrete example that uses
actual statements you can use in visual basic

Imagine that you owned a robot. This robot can do errands for you. It can go to the store
for you. It can cook you dinner and do your laundry. However, There’s a catch. You have
to program this robot.

Imagine that you want to send your robot to the store to purchase some groceries. But the
robot only understands commands such as MOVE LEFT FOOT and MOVE RIGHT
FOOT. You would have to send your robot to the store with hundreds or thousands of
commands. And the next day you would have to give your robot hundreds of commands to
send it to the post office. You can break the problem up into smaller components. You
could make a procedure WALK TO THE DOOR and another WALK TO THE END OF
THE BLOCK, etc. This would solve the problem of reusability. You could use the WALK
TO THE DOOR procedure again for the post office trip. Also it will probably be easier to
understand the problem if it is broken up into these easier to understand pieces.
Input and Output

You need to be able to tell your procedure what you want it to do and it needs to tell you
what the answer is. You can tell your procedure to behave differently based on input. The
input to a procedure is called its arguments or argument list.

The output is a return value. Subroutines do not have return values – they can only perform
tasks. Functions return values in addition to performing tasks.

There are two components to using procedures. First you have to write the procedure, then
you have to use it or call it.


-   A sub or subroutine is a procedure that performs a task but does not return a value
-   Syntax

       Sub SubroutineName (argName1 As dataType, argName2 As dataType…)
            lines of code to execute inside subroutine
       End Sub

-   Example without an argument list

       Sub ExitTheProgram()
             If (MsgBox(“Do you really want to exit?”, vbYesNo) = vbYes) Then
             End If
       End Sub

-   The click event handler is another example of a subroutine without an argument list.
-   Example of a subroutine with an argument list is

       Sub DisplayAnswer(intArg As Integer)
             Let lblAnswer.Caption = intArg
             Call MsgBox("The answer is: " & intArg)
       End Sub

-   The argument list looks a lot like a variable declaration
-   Each argument is referred to by the variable name you gave it within the argument list.
-   Exit a subroutine early by using the control statement Exit Sub.

Calling a Subroutine

Calling a subroutine is a statement just like an assignment statement or a control statement,
so you can call a subroutine from anywhere that you can use any other statement – that is –
within other procedures, such as event handlers. You cannot call a subroutine from the
Global Declarations area. The Global Declarations area is the area at the top of the code
view window where we normally place declarations and the Option Explicit statement.

-   Syntax

       Call SubroutineName (arg1, arg2, …)

-   Examples
       Call DisplayAnswer(10)
       Call DisplayAnswer(intAnswer)
       Call MsgBox("Hi there!”)
       Call MsgBox(txtAnswer.Text)
       Call ExitTheProgram

Variable Scope


-   A function is a procedure that returns a value
-   Syntax for writing a function

       Function FunctionName (argumentList) As dataType
             lines of code to execute inside function
             Let FunctionName = expression
       End Function

-   Example of a function

       Function DoubleIt(intArg As Integer) As Integer
             Let DoubleIt = intArg * 2
       End Function

-   Example for calling a Function

       Let intAnswer = DoubleIt(5)
Lab 10: Procedures
In this lab you will use procedures combined with the timer objects to create an animated
stick figure that will walk across your form.

                                         Part 1
Create the Project

   1. Start Visual Basic, and create a new project.
   2. Save the form and project as proc

Create the Controls

Create the following controls and place them on the form according to the picture below:

   1. Create 4 buttons for each of the following directions: Up, Down, Left, and Right.
   2. Create 4 timer objects for each of the following directions: Up, Down, Left, and
   3. Create a Stop button.

Your form should eventually look like this: (see the next step on how to get the arrows)
Set the Timer and Form Properties

   1. Select the form and set the following properties: MinButton to False, MaxButton to
      False, and WindowState to Maximized
   2. Set the (Name) property of the form to be frmBackGround.
   3. For each timer object, set its name (i.e. timUp, etc.) and set the Interval property to
      50 and set the Enabled property to False.
   4. Set the command button names and captions. To get the captions to appear as the
      example above, you can use the Wingdings 3 Font and the following characters:
      (You can just use the words Up, Down, Left and Right if you prefer)

Declare the Variables

You will need two variables in the global declaration space for the X and Y position of the
stick figure.

Initialize the Variables

Initialize your X variable so it contains the value from frmBackGround.Left.
Initialize your Y variable so it contains the value from frmBackGround.Top.

Write the drawStickPerson Procedure

   1. Type out the following procedure as shown below:

Sub drawStickperson(intX As Integer, intY As Integer)
  Circle (intX, intY - 750), 250
  Line (intX, intY - 500)-(intX, intY + 300)
  Line (intX - 500, intY - 300)-(intX + 500, intY - 300)
  Line (intX, intY + 300)-(intX - 300, intY + 800)
  Line (intX, intY + 300)-(intX + 300, intY + 800)
End Sub

Write the moveStickPerson Procedure

Create a procedure named moveStickPerson where the first parameter is intXAdd and the
second parameter is intYAdd. Inside the procedure add code to do the following:
   1. Erase the stick figure in its current position by doing the following:
          a. Add the following line of code:
              Let frmBackground.ForeColor = &H8000000F
          b. Call the procedure drawStickPerson passing you X and Y variables as the
   2. Set the X and Y variables to the new position by doing the following:
          a. Increment your X variable by intXAdd.
          b. Increment your Y variable by intYAdd.
   3. Redraw the stick figure in the new position by doing the following:
          a. Set the form color so the stick figure reappears by typing the following line:
              Let frmBackground.ForeColor = &HFF&
          b. Call the procedure drawStickPerson passing you X and Y variables as the

Create the Timer Event Handlers

For each timer object, double click on it to create the timer event for it. You should have
four timer events (i.e. timUp_Timer, timDown_Timer, timLeft_Timer, and
timRight_Timer). In each of these timer events, make a call to moveStickPerson passing an
increment value for either the X or Y position that will move the stick figure in the desired
position. See the table below:

                     Direction   X Increment     Y Increment
                     Up          0               -20
                     Down        0               20
                     Left        -20             0
                     Right       20              0

For example to move left use the following code:

       Call moveStickPerson(-20, 0)

Create the Click Events for Your Command Buttons

Create a click event for each command button. In each click event you are going to set the
Enabled property of each timer object to achieve the desired movement. For example, this
click event will move the stick figure down.

Private Sub cmdDown_Click()
       timUp.Enabled = False
       timLeft.Enabled = False
       timRight.Enabled = False
       timDown.Enabled = True
End Sub

Run You Program
                                          Part 2
In part two you will create tests for the boundaries of your form, so your stick figure does
not walk off the screen.

Create the BlnInRange Function

   1. Create a function named BlnInRange which takes the following parameters:
      intValue, intLow, and intHigh.
   2. In the function test that the parameter intValue is greater than intLow and less than
      intHigh. If it is, then return True otherwise, return False.

Use BlnInRange

We are going to test the X and Y values before incrementing them in the moveStickPerson
procedure. You are going to surround each of the two increment statements in your
procedure (the increment of you X variable and your Y variable) with If statements that call
BlnInRange and only execute the increment statement if the function returns True.

   1. For the X variable increment statement, test that BlnInRange returns true with the
      following parameters:

       Parameter Name        Value to Pass In
       intValue              Your X variable plus intXAdd
       intLow                frmBackGround.Left
       intHigh               frmBackGround.Left + (frmBackGround.Width – 3000)

   2. For the Y variable increment statement, test that BlnInRange returns true with the
      following parameters:

       Parameter Name        Value to Pass In
       intValue              Your Y variable plus intYAdd
       intLow                frmBackGround.Top
       intHigh               frmBackGround.Top + (frmBackGround.Height – 3000)

                                          Part 3
Add diagonal movement buttons (i.e. Up & Left, Up & Right, Down & Left, Down &
Right). In the click events for these buttons, set a combination of the timer objects to
enabled or disabled to achieve the desired movement. Do NOT add more timer events.
(The Wingdings 3 characters for diagonal arrows are:  = z,  = {,  = x, and  = y)

To top