Making Your Computer Do Something: Writing Your First Procedure

来源:互联网 发布:黄金比例公式算法 编辑:程序博客网 时间:2024/06/06 05:22

In this lesson, you will learn how to create a procedure, a self-contained block of code that can be run from other blocks of code, and then how to create parameters for your procedures.

A procedure is simply a piece of code that tells the program to perform an action. Although you may not have realized it, you have already used procedures in the previous lessons. For example, the MsgBox function is a built-in procedure that performs the action of displaying a dialog box.

While Visual Basic has many built-in procedures for performing common actions, there will always be cases when you want your program to perform an action that a built-in procedure can't handle. For example, the MsgBox function cannot display a dialog box with a picture. You need to write your own procedure to accomplish this task.
What is a Procedure?

A procedure is a self-contained block of code that can be run from other blocks of code. Generally speaking, procedures each contain the code necessary to accomplish one task. For example, you might have a procedure called PlaySound, which contains the code required to play a wave file. While you could write the code to play a sound every time your program needed to make a noise, it makes more sense to create a single procedure that you can call from anywhere in your program.

A procedure is run, or executed, by calling it in code. For example, to run the PlaySound procedure, you simply add a line of code to your program with the name of your procedure, as shown below.
PlaySound

That's all there is to it! When the program reaches that line, it will jump to the PlaySound procedure and execute the code contained there. The program will then jump back to the next line that follows the call to PlaySound.

You can call as many procedures as you like. Procedures are run in the order that they are called. For example, you might also have a procedure called DisplayResults; to execute it after executing the PlaySound procedure, call the procedures as shown below.

PlaySound

DisplayResults
Functions and Subs

There are two kinds of procedures: Functions and Sub routines (sometimes called Subs). A function returns a value to the procedure that called it, whereas a sub simply executes code. Subs are called when a line of code that contains the name of the sub is added to the program, as in the following example.

DisplayResults

Functions are different, because functions not only execute code, they also return a value. For example, imagine a function called GetDayOfWeek that returns an integer indicating the day of the week. You call this function by first declaring a variable in which to store the return value, and then assigning the returned value to the variable for later use, as shown below.

Dim Today As Integer
Today = GetDayOfWeek

In this example, the value returned by the function is copied to the variable named Today and stored for later use.
Writing Procedures

You write procedures by first writing a procedure declaration. A procedure declaration does several things: states whether the procedure is a function or a sub, names the procedure, and details any parameters the procedure might have (parameters will be discussed in detail later in this lesson). The following is an example of a simple procedure declaration.

Sub MyFirstSub()
End Sub

The sub keyword tells the program that this procedure is a sub and will not return a value. The name of the sub (MyFirstSub) comes next, and the empty parentheses indicate that there are no parameters for this procedure. Finally, the End Sub keyword indicates the end of the subroutine. All code that is to be executed by this Sub goes between these two lines.

Declaring Functions is similar, but with the added step that the return type (such as Integer, String, etc.) must be specified. For example, a function that returned an Integer might look like this.

Function MyFirstFunction() As Integer
End Function

The As Integer keywords indicate that this function will return an Integer value. To return a value from a function, use the return keyword, as shown in the following example.

Function GetTheNumberOne() As Integer
Return 1
End Function

This procedure will return the number 1.
Try It!

To create procedures
On the File menu, choose New Project.
 
In the New Project dialog box, in the Templates pane, click Windows Application.|
 
In the Name box, type MyFirstProcedure and then click OK.
A new Windows Forms project opens.
 
Double-click the form to open the Code Editor.
 
In the Code Editor, locate the line that reads End Class. This is the end of the code section that makes up your form. Immediately before this line, add the following procedure:

Function GetTime() As String
   Return CStr(Now)
End Function

This function uses the built-in Now procedure to get the current time, then uses the CStr function to convert the value returned by Now into a human-readable String. Finally, that String value is returned as the result of the function.
 
Above the function you added in the previous step, add the following sub.

Sub DisplayTime()
   MsgBox(GetTime)
End Sub

This sub calls the function GetTime and displays the result returned by it in a message box.
 
Finally, add a line to the Form1_Load event handler that calls the DisplayTime sub, as shown below.
DisplayTime()
 
Press F5 to run the program.
When the program starts, the Form1_Load event procedure is executed. This procedure calls the DisplayTime Sub, so program execution jumps to the DisplayTime Sub procedure. That Sub in turn calls the GetTime Function, so program execution then jumps to the GetTime Function. this function Returns a String representing the time to the DisplayTime Sub procedure, which then displays that string in a message box. After the sub is finished executing, the program continues normally and displays the form.
Parameters in Functions and Subs

At times you will need to provide additional information to your procedures. For example, in the PlaySound procedure, you may want to play one of several different sounds. You can provide the information on which sound to play by using parameters.

Parameters are a lot like variables. They have a type and a name, and they store information just like variables. They can be used just like variables in a procedure. The two main differences between parameters and variables are:

Parameters are declared in the procedure declaration, not in individual lines of code.

Parameters are usable only in the procedure they are declared in.

Parameters are declared in the procedure declaration in the parentheses that follow the procedure name. The As keyword is used to declare the type, and each parameter is generally preceded by the ByVal keyword. This keyword will be added automatically by Visual Basic if you do not add it, and it has a fairly advanced Function that is beyond the scope of this lesson to explain.

An example of a sub with parameters is shown below.

Sub PlaySound(ByVal SoundFile As String, ByVal Volume As Integer)
   My.Computer.Audio.Play(SoundFile, Volume)
End Sub

You would then call the sub with the values for the parameters as shown below.

PlaySound("Startup.wav", 1)

You can also declare parameters for Functions in exactly the same way you would for Subs.
Try It!

To create a function with parameters
On the File menu, choose New Project.
 
In the New Project dialog box, in the Templates pane, click Windows Application.
 
In the Name box, type parameters and then click OK.
A new Windows Forms project opens.
 
From the Toolbox, drag two Textbox controls onto the form.
 
From the Toolbox, drag a Button control onto the form.
 
Double-click the Button to open the Code Editor.
 
Immediately after the End Sub line of the Button1_Click event handler, add the following procedure:

Function AddTwoNumbers(ByVal N1 As Integer, ByVal N2 As Integer) _
As Integer
   Return N1 + N2
End Function
 
In the Button1_Click procedure, add the following code:

Dim aNumber As Integer = CInt(Textbox1.Text)
Dim bNumber As Integer = CInt(Textbox2.Text)

MsgBox(AddTwoNumbers(aNumber, bNumber))
 
This code declares two integers and converts the text in the two text boxes to integer values. It then passes those values to the AddTwoNumbers function and displays the value returned in a message box.
 
Press F5 to run the program.
 
Type a number value in each text box and click the button. The two numbers are added, and the result is displayed in a message box. 

原创粉丝点击