Sunteți pe pagina 1din 50

Visual Basic (VB) is the third-generation event-driven programming language and integrated development environment (IDE) from Microsoft

for its Component Object Model(COM) programming model. Visual Basic is relatively easy to learn and use. Visual Basic was derived from BASIC and enables the rapid application development (RAD) of graphical user interface (GUI) applications, access to databases using Data Access Objects and so on. Object has three characteristics and these are 1. Property : represents (data) characteristic of an object. 2. Method : represents the behavior (action) performed by an object. 3. Event : Event is message sent by an object to signal an activity. Creating A Project 1. Start VB6 2. When presented with a "New Project" dialog you will usually want to pick "Standard EXE" and press "Open" 3. You now see the VB6 IDE, which contains an empty form called "Form1". That is your program.

Forms In Visual Basic, the Form is the primary component of every GUI application. A form is a unique kind of control, known as a top-level container, a control that can contain within it any number of controls. Forms can come in many shapes and sizes, but typically they are solid gray boxes with a surrounding frame, a caption bar, and a variety of clip controls (a context menu, a close button, a minimize button, etc.). Create a form Forms can be created quite easily by starting a new project and selecting "Add Form..." from the project menu. If you specify this form as your project's start-up object (from Project / Properties), when you run this code, your form will appear, and the program will end when the form is closed. Changing Properties of Objects If you click on an object on your form, or even the form itself, you gain access to the properties of that item and change them in the properties pane on the right side of the screen. Running A Program Take a look in the menu item "Run". You will find that: Pressing "Start" in that menu, pressing the "Play" button, or pressing F5 on your keyboard will run your program Pressing "End" in that menu, or pressing the "Stop" button will stop your program. Getting into the source code Right-click anywhere on the form called "Form1", and select "View code". Another way to accomplish the same thing is to double-click anywhere on the form. Setting project properties In the top menu click on Project Project1 Properties
Page 1 of 50

Variables A variable is a word or letter used to reference data used in a program. Variable Names The following are the requirements when naming the variables in Visual Basic: It must be less than 255 characters No spacing is allowed It must not begin with a number Period (.)is not permitted

In Visual Basic we define a variable name by using the keyword Dim. Dim stands for "dimension" which is a carry over from early programming days. When you define a variable, you also specify what type of data it is allowed to hold. Below is a list of all the different data types and what data they can hold.

Page 2 of 50

General Data Types TYPE Boolean Byte Double Integer Long Single String Can Hold True or False A number 0 to 255 A 64 bit floating point number (I.E. 3.1415) - This is used when a high degree of accuracy is needed. A whole number from -32768 to 32767 A whole number from -2,147,483,648 to 2,147,483,647 A 32 bit number like a double, but with less precision A collection of letters such as "Hello". This is used to store words and sentences.

Without using a variable Private Sub Command1_Click() ' Execute a simple message box that will say "Hello, World!" MsgBox "Hello, World!" End Sub Using variable Private Sub Command1_Click() Dim var1 As String var1 = "Hello, World!" MsgBox var1 End Sub Private Sub Form_Load() Dim a As Integer Dim b As Integer Dim c As Integer a=5 b=5 c=a+b MsgBox c End Sub MsgBox TextUser.Text & " " & TextPassword.Text Unload FormLogOn Or Unload me Option Explicit Dim Count As Integer
Page 3 of 50

Private Sub Form_Load() Count = 0 Timer1.Interval = 1000 ' units of milliseconds End Sub Private Sub Timer1_Timer() Count = Count + 1 Label1.Caption = Count End Sub A conditional statement A conditional statement is a way for you to execute commands based on if a condition is true. With an ifstatement, you can evaluate an expression, and perform one task if that expression is True and perform another if it's False. The If-Then Statement If (Expression) Then (Multiple lines of code to execute) End If Private Sub Command1_Click() Dim var1 As Integer var1 = 10 The If-Then-Else Statement If (Expression) Then (Code to execute if True) Else (Code to execute if False) End If If var1 = 10 Then MsgBox "The condition is true." End If End Sub

Private Sub Command1_Click() Dim var1 As Integer var1 = 5 If var1 = 10 Then MsgBox "The variable is ten" Else MsgBox "The variable is not ten" End If End Sub pseudo code 1. Let x = 1, let y = 0. 2. Print x. 3. Let x = y + x
Page 4 of 50

4. Let y = x - y 5. Repeat from 2. This pseudo code will print out: 1, 1, 2, 3, 5, 8, 13, 21, ... as expected. LOOPS Loops provide the ability to repeatedly execute the same block of code, and to each time change values such that each run through the loop produces different results. Visual Basic provides four main kinds of loops: the classic Do-Loop, the Do-Until Loop, the Do-While Loop, and the For-Next Loop.

Do-Loops The most basic form of loop in Visual Basic is the Do-Loop. Its construct is very simple: Do (Code to execute) Loop

generating the Fibonacci series: Dim X As Integer Dim Y As Integer Do Debug.Print X X=Y+X Y=X-Y Loop

Exit Do So we clearly need some way to escape from the Do-Loop. Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. cnt = 1 Do Debug.Print X X=Y+X Y=X-Y If cnt >= 8 Then
Page 5 of 50

Exit Do Else cnt = cnt + 1 End If Loop End Sub Do While In the place of Do Until, you can also use Do While. Its syntax is the following: Do While (Expression) (Code to execute) Loop (Expression) can be any legal logical expression that we wish to evaluate to determine whether or not to exit the loop. Each time the program reaches Loop it will verify that this expression is True, and if it is False, it will exit the loop for us. Thus, instead of exiting when an expression is True, it now exits only once this expression is false. Let's try rewriting our Fibonacci program to use a Do-While loop instead of a Do-Until loop. Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. cnt = 1 Do While cnt < 8 Debug.Print X X=Y+X Y=X-Y cnt = cnt + 1 Loop End Sub For-Next Loops In situations where you merely want to run the loop a predefined number of times, it can become quite tiresome to have to create and manage a counter for each loop, which is why we also have something called a For-Next Loop. This kind of loop allows you to specify a counter, to tell it to count from one number to another each time through the loop, and to exit once the counter has reached its upper limit. The syntax is as follow: Dim I As Integer For I = (Integer) To (Integer) (Code to execute) Next I

Page 6 of 50

We used the variable name "I" above, as it is the most common name used for For-Loops; however, you can use any variable name you want, so long as the variable is of the type Integer. Now, let's improve our Fibonacci program even further: Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. For cnt = 1 To 8 Debug.Print X X=Y+X Y=X-Y Loop End Sub

In the example above, we first dimensioned cnt as an Integer, and then, in the declaration of the For-Next loop, set its value to 1. Each time through the loop, the value of cnt was incremented by 1 until it reached 8, at which point the loop was executed. Exit For As with Do Loops, there is a statement that can be used to exit a For-Next loop, and it is called Exit For. Simply invoke this statement anywhere within a For-Next loop and the current loop will be exited. Step By default, the variable used in the declaration of the For-Next loop is incremented by 1 each time through the loop; however, if you want to increment this value by a different amount each time through the loop, you can simply append Step (Integer) to the end of the For-Next loop declaration. If, for instance, we wanted to print out every even number counting backward from 20 to 0, we could do this using the following code: Dim I As Integer For I = 20 To 0 Step -2 Debug.Print I Next I Functions and subroutines What Are Subroutines? Subroutines can be thought of as miniature programs. A subroutine has a name attributed with it, much like a variable does. Unlike a variable, a subroutine doesn't hold data. Instead, it holds code. When the code in a subroutine is executed, the subroutine is said to be "called". Therefore, one subroutine can "call" another subroutine. Some subroutines are called automatically when certain actions are performed. For example, the Form_Load subroutine is automatically called when a form loads. This is where you have been inserting your test code before. What you were actually doing was adding code to this subroutine. A Note On Form_Load
Page 7 of 50

Technically, Form_Load isn't really a subroutine, it is a special type of subroutine called an EVENT. Why Use Subroutines? eliminate redundancy. making the entire program easier to manage. debug the codes in more concise and efficient way.

Creating A Subroutine Creating a subroutine involves two lines of code. A subroutine begins with the word "Sub", followed by a space, then a name identifying the subroutine. Two parentheses follow, which are used for a parameter list. Sub TestSub() End Sub After you enter the first line and press Enter, the second line will automatically be added for you. These lines represent the start and end of the subroutine. Any code inserted between these lines will be executed when the subroutine is called. A subroutine can be called in one of two ways: using the Call keyword, or by simply stating its name. Sub TestSub() MsgBox "Code in TestSub()" End Sub Private Sub Form_Load() MsgBox "Code in Form_Load()" TestSub MsgBox "Back in Form_Load()" End Sub You can also use the Call keyword, as mentioned above: Sub TestSub() MsgBox "Code in TestSub()" End Sub Private Sub Form_Load() MsgBox "Code in Form_Load()" 'This line is functionally equal as the line in the previous example Call TestSub MsgBox "Back in Form_Load()" End Sub Comments The previous listing introduced a new syntax element: the comment. A comment is a line that is NOT source code. Instead, it is there as guidance to the person reading the code. When programmers write programs, they usually (or at least they should) add comments describing large sections of code that could potentially be confusing. Comments begin with an apostrophe ("'") and end with a new line. Everything that you type after the apostrophe is ignored by Visual Basic, which is the entire point of comments. You will see comments in all future listings describing new concepts and syntax.
Page 8 of 50

Subroutine Scope The declaration of a subroutine has an optional keyword that can be used before "Sub". You may enter a keyword representing scope here. "Private" and "Public" are examples of scopes. You may have noticed that the Form_Load subroutine has the word "Private" before "Sub". This declares that this subroutine has a Private scope. If you don't specify the scope of a subroutine, Visual Basic will use a default scope. You should never rely on default scope, however. Get in the habit of always explicitly declaring the scope of your subroutines. What Is Scope? In the context of subroutines, scope represents where in your program the subroutine can be called from. Subroutines with a Private scope can only be called from the source file from where they were defined. Subroutines with a Public scope can be called from anywhere in your program. For example, a subroutine with a Private scope in a form can not be called from another form, whereas it can if it has a Public scope. Why Use Scope? Why would you ever limit where you can call a subroutine from? Why wouldn't you make all subroutines Public so that there are no limitations on your program? Subroutine Scope is one of many tools that programmers can use to find bugs. If you know that your subroutine should never be called from a different source file, you should declare the subroutine to be Private. This will prevent you from making a silly mistake and calling this subroutine where it shouldn't be called. This will prevent mistakes that could be extremely damaging and hard to detect. Instead, your program will crash with an error rather than executing the subroutine with unpredictable results. Parameters Parameters, also called Arguments, are variables that can be "passed into" a subroutine. A subroutine with parameters looks like this: Private Sub DisplayAdd(x As Integer, y As Integer) MsgBox x + y End Sub Private Sub Form_Load() DisplayAdd 5, 2 End Sub A new subroutine has been declared called DisplayAdd. This declaration is different than the declarations that you have seen so far, however, as code has been added between the parenthesis. From your knowledge of variables, this syntax should look somewhat similar to you. x As Integer and y As Integer appear to be variable declarations without the "Dim" keyword. These declarations are separated by a comma. These variables are the Parameters for the DisplayAdd subroutine. Code within the subroutine can access x and y as usual, as if they were normal variables. However, when the subroutine is called, the calling subroutine will also provide values for these parameters. Therefore, the subroutine has now become dynamic. The code can act on input without caring where the input came from. When the Form_Load subroutine calls DisplayAdd with the parameters 5 and 2, the code within DisplayAdd is executed. The first line adds x and y together and displays the result. x and y have already been filled with the values 5 and 2 from the
Page 9 of 50

Form_Load subroutine. The calling subroutine doesn't have to use numeric constants, however. It can use variables as well: Private Sub DisplayAdd(x As Integer, y As Integer) MsgBox x + y End Sub Private Sub Form_Load() Dim a As Integer Dim b As Integer a=5 b=2 DisplayAdd a, b End Sub This code has identical results. Note that DisplayAdd cannot access a and b. As far as DisplayAdd is concerned, a and b are represented as x and y. Attempting to access a or b from DisplayAdd would result in an error. ByRef and ByVal Parameters can be sent to a subroutine By Reference (ByRef) or By Value (ByVal). ByRef is the default, and means that changes to the variable in the subroutine will result in changes to the source variable outside of the subroutine. ByVal literally copies the values of the variables from the calling subroutine into the called subroutine. By doing this, the variables can be changed, but their values will not change outside of the called subroutine. ByVal can also be a lot slower with large variable types, however, since memory has to be copied from one location to another. If you don't have any reason to do so, there is no need to pass variables ByVal. You can explicitly state the way that a variable is passed to a subroutine by using these keywords before the variable name. Using the ByRef keyword, one could write a Swap function, which switches the values of 2 variables. Private Sub Swap(ByRef x As Integer, ByRef y As Integer) Dim temp As Integer temp = x x=y y = temp End Sub Private Sub DisplayVals(ByRef a As Integer, ByVal b As Integer) 'Don't worry about understanding the next line yet, it will be explained later MsgBox "a = " & CStr(a) & vbCrLf & "b = " & CStr(b) End Sub Private Sub Form_Load() Dim a As Integer Dim b As Integer a = 10 b = 12
Page 10 of 50

'Display values, swap, and display again DisplayVals a, b 'The next line is functionally identical to "Swap a, b" Call Swap(a, b) DisplayVals a, b End Sub Notice that Call was used instead of simply stating the subroutine name. When using the Call method however, you must use parenthesis when calling the subroutine. Note that this program would also have worked without typing "ByRef" anywhere, since it is the default. The ByRef and ByVal keywords are rarely used in simple programs, however, but it's a nice trick for your toolkit. Functions Subroutines have a close cousin called Functions. Functions are basically the exact same as subroutines, except that they return a value. That means that the function itself has a type, and the function will return a value to the calling subroutine based on the code that it contains. An example of this would be a function that adds two numbers, shown below. A function is declared the exact same way as a subroutine, except using the "Function" keyword instead of "Sub". To return a value, assign a value of the proper type to the function's name, as if it were a variable. Private Function Add(ByVal x As Integer, ByVal y As Integer) As Integer Add = x + y End Function Private Sub Form_Load() Dim a As Integer Dim b As Integer Dim c As Integer a = 32 b = 64 c = Add(a, b) MsgBox c End Sub Functions Or Subroutines? The best way to determine which is better for your application is by asking yourself a simple question. Will you need to return a value? If so, use Functions. If you don't, use subroutines.

Overview If you've read some other beginner visual basic tutorials on this site, you're probably saying to yourself, "I thought this was supposed to be Visual Basic!" Indeed, Visual Basic is very much so an interface-oriented language, far moreso than other languages, and designing even complex graphical user interfaces (or GUIs) is quite simple.

Page 11 of 50

In contrast to tradional, command-line interfaces, almost all user interfaces in Visual Basic are constructed using the WIMP, or "windows, icon, menu, pointer," GUI style. This means that Visual Basic programs interact with users almost exclusively using graphical elements, such as windows, buttons, toolbars, etc., with very few console-based applications (in fact, creating a console-based VB application is quite difficult, requiring advanced API techniques, which will be covered much later). While in previous lessons, we've made use of Debug.Print, which is not a WIMP element, it's important to note that the debugging, or intermediate, window is only visible in design mode, and not during typical program execution. In this tutorial, we'll introduce and expand upon three basic methods of creating WIMP interfaces in Visual Basic: using the MsgBox function (which you've seen before), the InputBox function, and forms and controls. MsgBox revisited Up until now, we've blindly used this magical MsgBox function to display text without really understanding what it was, how it worked, or what could be done with it. Now that we have a bit more understanding of functions, subroutines, and control structures, let's take a somewhat closer look at it. MsgBox is a actually a function, like many of the functions we've used and created before, provided by the standard VB runtime. Its function declaration is the following: Public Function MsgBox( _ ByVal prompt As String, _ Optional ByVal buttons As Integer = vbOKOnly, _ Optional ByVal title As String = Nothing _ Optional ByVal helpfile As String = Nothing _ Optional ByVal context As Integer = Nothing _ ) As Integer Having read Functions and Subroutines in VB6, you should now be able to recognize a few useful attributes of the MsgBox function. For one, MsgBox has a return type--Integer, which implies that we can not only display data in a MsgBox, but also get information back. The information we are able to retrieve from calling the MsgBox function is a numerical expression equating to a constant value that describes which button on the MsgBox was clicked. Legal return values for the MsgBox function are: vbOK, vbCancel, vbAbort, vbRetry, vbIgnore, vbYes, and vbNo. Furthermore, we can specify which buttons and styles we want displayed on our message boxes using the "buttons" argument. If, for instance, we want to display a msgBox with the buttons "Abort," "Retry," and "Ignore," we can use the construct: MsgBox "Test", vbAbortRetryIgnore. If we further want to display this message box with a "Question" icon, we can use this construct: MsgBox "Test", vbAbortRetryIgnore + vbQuestion. There are many possible values for the button argument, and you can find a full list in the MSDN library. With the title argument, we can also change the text we want to display in the caption of the message box by passing any legal String. The "helpfile" and "context" arguments will be explained later on in the course when we cover contextual help in VB6. MsgBox examples Now let's took a look at a simple example that makes use of MsgBox.
Page 12 of 50

Public Sub Main() If MsgBox("Click a button.", vbOKCancel, "MsgBox Test") = vbOK Then MsgBox "You clicked OK!", vbOKOnly, "MsgBox Test" Else MsgBox "You clicked Cancel!", vbOKOnly, "MsgBox Test" End If End Sub And voila! We have a program that's capable of responding to user input! Now what if we to give the user three different options? We could do this: Public Sub Main() If MsgBox("Click a button.", vbYesNoCancel, "MsgBox Test") = vbYes Then MsgBox "You clicked Yes!", vbOKOnly, "MsgBox Test" ElseIf MsgBox("Click a button.", vbYesNoCancel, "MsgBox Test") = vbNo Then MsgBox "You clicked No!", vbOKOnly, "MsgBox Test" Else MsgBox "You clicked Cancel!", vbOKOnly, "MsgBox Test" End If End Sub However, you may notice one major probelm with this code: it displays two message boxes instead of just one, which is what we expected. This is because each time you call MsgBox, a new message box is created. To respond to three different return types for one MsgBox, it's best to store the value in a variable and then perform tests on that variable. For example: Public Sub Main() Dim ret As Integer ret = MsgBox("Click a button.", vbYesNoCancel, "MsgBox Test") If ret = vbYes Then MsgBox "You clicked Yes!", vbOKOnly, "MsgBox Test" ElseIf ret = vbNo Then MsgBox "You clicked No!", vbOKOnly, "MsgBox Test" Else MsgBox "You clicked Cancel!", vbOKOnly, "MsgBox Test" End If End Sub InputBox Now let's take a quick look at a function similar to MsgBox that allows the user to provide a much, much wider array of valid inputs, namely the InputBox function. This function is provided by the standard VB6 runtime, and its declaration is as follows: Public Function InputBox( _ prompt As String, _ Optional title As String = Empty, _ Optional default As String = "", _ Optional xpos As Single = Empty, _ Optional ypos As Single = Empty, _ Optional helpfile As String = Empty, _
Page 13 of 50

Optional context As Integer = 0 _ ) As String This function displays an InputBox, or a single dialog requesting a single line of ASCII input from the user, with the given prompt, title, default text (specified by default), and other argument values (which we won't get into in depth) and returns the String that the user provided the dialog. Let's take a look at a simple example: Public Sub Main() Dim YourName As String YourName = InputBox("Please enter your name.", "InputBox demo") If Len(YourName) > 0 Then MsgBox "Your name is " + YourName Else MsgBox "You hit cancel or entered an empty string." End If End Sub This simple little program prompts the user for his or her name and then displays it in a MsgBox. If the user selected cancel the string returned will be an empty string (""). This very simple function now allows your program to behave in an infinite number of ways, as the InputBox dialog can except an infinite number of various inputs.

Properties of forms Like all controls, forms have a variety of properties associated with them. Some of these properties can be set at runtime or by modifying them in the Properties Window. To access the Properties Window, simply select the Form (in design mode, of course), and you should see the properties for the form appear in the right-most docking-window directly beneath the Project Explorer. From here, you can change almost every property of your form. The most important property of a form is its Name. This property can be set only at design, and should appear as the first item in the properties list. You can set this to anything you want; however, it is common convention that all form names begin with a form identifier, such as "Form" or "frm". By default, the first form in a project is named "Form1," the second "Form2," etc. Choosing a clear, descriptive name for your forms is very important because everytime you call methods on or change the properties of a form from runtime, you will use the form's name as an identifier. Another important property of a form is its Caption. This property specifies what text will be displayed in the form's caption bar. You can change it by selecting "Caption" from the properties list, and then specifying any single line of text you would like. You can adjust the width and height of your forms by either explicitly specifying the property in the Properties Window or by simply resizing the form in design mode. There are many other physical properties of forms that we won't get into here, but please, feel free to play around with them. Form modules So far, every VB6 application we've dealt with has been executed from a Basic module (or .bas file), by creating a project, adding a new module, and adding to that module a Public Sub Main(). In traditional
Page 14 of 50

BASIC, all programs were constructed this way; however, with the advent of Visual Basic a new kind of module, known as a form module, was introduced. A form module is a unique kind of module that contains code that is owned by one, and only one, form. Every form has one, and only one, form module associated with it, and form modules contain all of the code that can be directly invoked by the form or by controls contained by the form in response to an action by the user. The code in these modules can only be accessed once the form is constructed, and form modules typically contain primarily only Private subroutines and functions, though they may also contain Public helper routines to allow accessibility to components of the form to other modules. To access a form's code module, simply select the form in the Project Exlporer, right-click, and select "View Code." This will open up an empty editor window like we're used to seeing with Basic modules--the only difference is what we can put in a form module. The most common starting point for a form is Private Sub Form_Load(). This routine is called immediately after the form is created and drawn, but before the form has begun waiting for user input. To start, let's try rewriting an example you've seen before to use Form_Load() instead of Main(): Private Sub Form_Load() MsgBox "Hello, world!" End Sub Immediately after this form is loaded, a MsgBox will be displayed with the text "Hello, world!". It is important to note that every form can have a Private Sub Form_Load() and that, unlike with Sub Main, the Form_Load routine can be accessed only by the form module (due to its Private access). The "Me" identifier Now let's say we want to access the properties and methods of our form from within our form module. We could use something like Form1.Caption = "Hello, world!", but this is very bad practice, as you'll understand fully once we begin dealing with ActiveX controls and control arrays (much later on!). Instead, Visual Basic provides an identifier known as the "Me" ientifier, which is simialr to "this" in languages such as C and Java. It allows us, basically, to access ourselves--that is, the form module it's used in. For example: Private Sub Form_Load() Me.Caption = "Hello, world!" End Sub This will change the Form's caption to "Hello, world!" after the form is loaded, regardless of what property we specified at design-time. The Show and Hide Methods

The Show method of a form displays that form on the screen. If the form to be shown is not already loaded into memory, the Show method will load it before showing it. The Show method is typically used to transfer control from one form to another. The syntax is:

formname.Show

For example, if I am in Form1 and I want to display Form2, the syntax would be:
Page 15 of 50

Form2.Show

When you display one form from another, you may want the user to complete work on that form before returning to the first one. This does not happen automatically. By default, VB will display the second form and then continue executing code from the first form. To suspend execution of the first form until after the second form is done with, add the keyword constantvbModal as an argument to the Show method. The syntax is:

Form2.Show vbModal

The Hide method of a form removes the form from the screen (makes it invisible), but the form still remains in memory. The syntax is:

formname.Hide

To refer to the form in which code is currently running (i.e. the "current" form, or the "active" form), you can of course refer to the form by its name, as in the example above:

Form1.Hide

As an alternative, you can use the keyword Me. The keyword "Me" refers to the form in which code is currently running:

Me.Hide

Finally, any time you want to execute a method of the form on itself, you can simply code the method name, omitting the "formname." or the "Me.", as in:

Hide

The Load and Unload Statements


Page 16 of 50

The Load statement loads a form into memory, but does not display it. When you code the Load statement for a form, the Form_Load event of that form will be triggered. The syntax is:

Load formname

The Unload statement removes a form from memory and from the screen. When you code the Unload statement for a form, the Form_Unload event of that form will be triggered. The syntax is:

Unload formname

A form can unload itself, as in:

Unload Me

The Unload event is also triggered with the user clicks the Windows "close" button ("X") on the form.

Try this: Place a command button named "cmdExit" with the caption "Exit" on a form. In the Click event for the command button, instead of coding "End", code:

Private Sub cmdExit_Click()

Unload Me

End Sub

For the Form_Unload event, code the following:

Private Sub Form_Unload(Cancel As Integer)

Page 17 of 50

If MsgBox("Are you sure you want to quit?", _ vbYesNo + vbQuestion, _ "Unload Test") = vbNo Then Cancel = 1 End If

End Sub

Run the program and observe what happens either when you click the Exit button, or when you try to close the form by clicking on the "X" button.

Note that VB supplies the Unload event with a built-in argument called "Cancel". If, in the Unload event procedure, you set the Cancel argument to any non-zero value, the Unload event will be cancelled (i.e., the form will not be unloaded) and processing will continue. This event is where you might ask the user if they are sure they want to quit. If they respond Yes, let the Unload event "do its thing"; if No, set Cancel to nonzero value.

Note: When all forms of a VB project are unloaded, the application ends. The End statement automatically unloads all forms in a project, but will not trigger the Unload event (so any code you have in the Unload event will not execute) therefore, ending an application with "End" does not give the user a second chance to keep working with the program. The End statement ends the program abruptly.

Centering a Form on the Screen

The following code will center a form on the screen. It is best placed in the Form_Load event.

Me.Top = (Screen.Height Me.Height) / 2 Me.Left = (Screen.Width Me.Width) / 2

In VB project that has multiple forms, it is a good idea to centralize the form-centering logic in a Public Sub procedure of a separate standard (BAS) module. The sub, which accepts a Form object as a parameter, would look like this:

Public Sub CenterForm(pobjForm As Form)


Page 18 of 50

With pobjForm .Top = (Screen.Height .Height) / 2 .Left = (Screen.Width .Width) / 2 End With

End Sub

With the above Sub in place, any form in the project can center itself with the following line of code:

CenterForm Me

Form_Load vs. Form_Activate

In the Form_Load event, you would typically perform initialization-type tasks, as you should. However, certain types of actions cannot be performed in the Load event, due to the fact that the form is fully loaded only after the Load event completes. For one thing, printing to the form will not work when done in the Load event. In addition, if you try to set focus to a particular control on the form during the Load event, you will get the message Run-time error '5': Invalid procedure call or argument. For example, assume you had a textbox called Text1 on the form. The following code would result in that error:

Private Sub Form_Load()

' other initialization stuff

Text1.SetFocus ' causes an error

End Sub

The reason for the error is that since the form is not fully loaded, neither are any of the controls on it and you can't set focus to a control that is not yet available. To remedy this problem, you should use one of the other Form events, such as the Activate event. (When VB loads a form, it actually cycles through a number of events, such as: Initialize, Load, Resize, Activate,
Page 19 of 50

GotFocus, and Paint. Of these, Load and Activate are probably the ones most commonly used. ) Placing the code to set focus to a control will work in the Form_Activate event:

Private Sub Form_Activate()

' other statements

Text1.SetFocus ' no problem here

End Sub

A caution about the activate event: it will fire whenever your application switches to that form. For example, if you switch back and forth between Form1 and Form2, be aware that any code you might have in the Activate events for these forms will be executed when you switch to that form. Therefore, if you have code in the Activate event that you only want to execute "the first time", you will need to control execution with a Boolean switch. For example, in the General Declarations of your form you could define the following variable:

Private mblnFormActivated As Boolean ' will be initialized to False by default

You can then use this switch in the Activate event as follows:

Private Sub Form_Activate()

If mblnFormActivated Then Exit Sub

' statements you only want to execute once, including the following ' statement to turn the switch on:

mblnFormActivated = True

End Sub
Page 20 of 50

Multi-Form Projects

Many projects will use more than one form. When you have more than one module (form or standard) in a project, you must specify a "Startup object", which is done via the Project menu, Properties item. The startup object tells VB which form or standard module is to have its code run first (if a standard module is the startup object, it must contain a public subroutine called "Main", and "Sub Main" is specified for the Startup object). By default, the startup object is the initial form that is supplied with every new VB Project.

Here are a couple of scenarios for projects with multiple forms:

(1)

You have an application that performs a variety of functions, requiring multiple "screens" (forms). You can use one form as a "switchboard" or "main menu" form that connects to the other forms. You may wish to have a "splash screen" start off your application before the main form is displayed.

(2)

Using Multiple Forms: "Switchboard" Example

Assume you have a project with three forms: Form1, Form2, and Form3. (To add forms to a project, go to the Project menu and select Add Form.) Form1 serves as the switchboard form, which contains three command buttons: cmdForm2, cmdForm3, and cmdExit:

Page 21 of 50

The code behind these buttons is:

Private Sub cmdForm2_Click() Form2.Show vbModal End Sub

Private Sub cmdForm3_Click() Form3.Show vbModal End Sub

Private Sub cmdExit_Click() Unload Me End Sub

For the sake of the example, Form2 and Form3 simply contain one button with the caption "Return to Main Menu". The code behind the command button on each of these forms is simply Unload Me. When either of these forms is unloaded, the main menu form will then become the active form.

Download the VB project code for the example above here.

Page 22 of 50

*** BONUS MATERIAL *** (Form Procedures) Presented below is a set of procedures that can be used to work with forms. The code presented can be saved as a .BAS module (for example, modForm.bas) and can be included and used in any VB6 project.

The set of procedures is described below:

Procedure Name

Description

CenterForm

Centers a form on the screen. This Sub has been used in previous examples presented site.

Usage: CenterForm FormName

(where FormName is the name of the form without quotes (e.g. Form1) or the keywor

To center the current form, you would use: CenterForm Me

FormIsLoaded

Function that determines whether or not a form in your app is currently loaded. It does searching through the VB Forms collection. It accepts a string parameter containing th the form that you want to check and returns a Boolean.

Usage: If FormIsLoaded("Form1") Then ...

EnableFormXButton

Sub that lets you enable or disable the form's "X" (or "Close") button that appears in th hand corner of the form's title bar. (A common usage is to disable the X button.) This wrapper for a handful of APIs that work together to accomplish this task (GetSystemM GetMenuItemCount, RemoveMenu, DrawMenuBar).

Page 23 of 50

Usage: EnableFormXButton FormName, BooleanValue (where FormName is the name of the form without quotes (e.g. Form1) or the keyword Me andBooleanValue is True or False)

To disable the X button on Form1, you would use: EnableFormXButton Form1, False

MakeTopmost

Sub that lets you keep a form "always on top", even if it does not currently have the fo Sub will also let you reverse the action and make the form "not" always on top. This S wrapper for the SetWindowPos API.

Usage: MakeTopmost FormName, BooleanValue (where FormName is the name of the form without quotes (e.g. Form1) or the keyword Me andBooleanValue is True or False)

To make the current form "always on top", you would use: MakeTopmost Me, True

LockWindow / UnlockWindow

The purpose of these Subs is help avoid "flicker" when controls and their contents tak than usual to populate on a form. These Subs are a wrapper for the LockWindowUpda which disables drawing in the given window. Only one window can be locked at a tim

Usage (to lock): LockWindow FormName.hwnd Usage (to unlock): UnlockWindow

The code is given below:

Option Explicit

Private Declare Function DrawMenuBar Lib "user32" (ByVal hwnd As Long) As Long
Page 24 of 50

Private Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As Long, ByVal bRevert As Long) As Long Private Declare Function GetMenuItemCount Lib "user32" (ByVal hMenu As Long) As Long Private Declare Function LockWindowUpdate Lib "user32" (ByVal hwnd As Long) As Long Private Declare Function RemoveMenu Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long) As Long Private Declare Sub SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal Y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long)

Private Const MF_BYPOSITION As Long = &H400& Private Const MF_REMOVE As Long = &H1000& Private Const HWND_TOPMOST As Long = -1 Private Const HWND_NOTOPMOST As Long = -2 Private Const SWP_NOSIZE As Long = &H1 Private Const SWP_NOMOVE As Long = &H2 Private Const SWP_NOACTIVATE As Long = &H10 Private Const SWP_SHOWWINDOW As Long = &H40

'============================================================================= ' Form-related Routines '=============================================================================

'----------------------------------------------------------------------------Public Sub CenterForm(pobjForm As Form) '-----------------------------------------------------------------------------

With pobjForm .Top = (Screen.Height - .Height) / 2 .Left = (Screen.Width - .Width) / 2 End With

Page 25 of 50

End Sub

'----------------------------------------------------------------------------Public Function FormIsLoaded(pstrFormName As String) As Boolean '----------------------------------------------------------------------------Dim objForm As Form For Each objForm In Forms If objForm.Name = pstrFormName Then FormIsLoaded = True Exit Function End If Next FormIsLoaded = False

End Function

'----------------------------------------------------------------------------Public Sub EnableFormXButton(pobjForm As Form, pblnEnable As Boolean) '-----------------------------------------------------------------------------

Dim lngSysMenuID As Long Dim lngMenuItemCount As Long ' Get handle To our form's system menu ' (Contains items for Restore, Maximize, Move, Close etc.) lngSysMenuID = GetSystemMenu(pobjForm.hwnd, pblnEnable)

If lngSysMenuID <> 0 Then ' Get System menu's menu count lngMenuItemCount = GetMenuItemCount(lngSysMenuID) If lngMenuItemCount > 0 Then
Page 26 of 50

' Remove (hide) the "Close" item itself (the last menu item) ... RemoveMenu lngSysMenuID, lngMenuItemCount - 1, MF_BYPOSITION Or MF_REMOVE ' Remove (hide) the seperator bar above the "Close" item ' (the next to last menu item) ... RemoveMenu lngSysMenuID, lngMenuItemCount - 2, MF_BYPOSITION Or MF_REMOVE End If End If DrawMenuBar pobjForm.hwnd End Sub

'----------------------------------------------------------------------------Public Sub LockWindow(hwnd As Long) '----------------------------------------------------------------------------LockWindowUpdate hwnd End Sub

'----------------------------------------------------------------------------Public Sub UnlockWindow() '----------------------------------------------------------------------------LockWindowUpdate 0 End Sub

'----------------------------------------------------------------------------Public Sub MakeTopmost(pobjForm As Form, pblnMakeTopmost As Boolean) '-----------------------------------------------------------------------------

Dim lngParm As Long lngParm = IIf(pblnMakeTopmost, HWND_TOPMOST, HWND_NOTOPMOST) SetWindowPos pobjForm.hwnd, _ lngParm, _
Page 27 of 50

0, _ 0, _ 0, _ 0, _ (SWP_NOACTIVATE Or SWP_SHOWWINDOW Or _ SWP_NOMOVE Or SWP_NOSIZE)

End Sub The TIMER Control

The Timer control allows you to perform a task at a specified interval or to wait for a specified length of time.

Timer Example 1

Start a new VB project and place two command buttons and a timer control on the form. Set the properties of the controls as follows: Control Property Value Command Button (Name) cmdStart Caption Start Timer

Command Button (Name) cmdStop Caption Stop Timer

Timer (Name) tmrTest Enabled False Interval 250

Your form should look something like this:

Page 28 of 50

Consider the following facts about the Timer control: It is not visible to the user at run-time The actions that you want to happen at the specified interval are coded in the Timer's Timer event. You specify the interval that you want actions to occur in the Timer control's Interval property. The value is specified in milliseconds (1000 milliseconds = 1 second). In the example, the value of 250 will cause the Timer event to fire every quarter of a second. You turn the timer "on" or "off" by setting its Enabled property to True or False, respectively. The Enabled property is set to True by default.

Place the following declaration in the Form's General Declarations section: Private mintCount As Integer

Code the Click event for the two command buttons and the Timer event for the timer control as follows: Private Sub cmdStart_Click()

mintCount = 0 Cls tmrTest.Enabled = True


Page 29 of 50

End Sub

Private Sub cmdStop_Click()

tmrTest.Enabled = False

End Sub

Private Sub tmrTest_Timer()

mintCount = mintCount + 1 Print "Timer fired again. Count = " & mintCount End Sub

Run the program. Click the "Start Timer" button. Messages will appear on the form every quarter of a second. They will stop when you click the "Stop Timer" button. A sample run might look like this:

Page 30 of 50

Download the VB project code for the example above here.

Timer Example 2

The Timer control can be used to make an object on your screen appear to blink. This is done by toggling the Visible property of the object on and off at short intervals. The Visible property is available to nearly all controls it is a Boolean property that determines whether or not the control is visible to the user at run time by setting its value to True or False (it will always be visible at design time). To build a simple demo, perform the following steps.

Start a new VB project. Place a label on the form and name it lblProcessing. Set its Caption to Processing . . . Please Wait. Set it to a large font and set its Forecolor property to the color of your choice. Center it on your form. Place a timer on the form and name it tmrBlink. Set its Interval property to 250. In the tmrBlink_Timer event, place the following single line of code: lblProcessing.Visible = Not lblProcessing.Visible

Run the project. The label will blink. After an appropriate period of observation, close the form.

And now on to the Splash Screen example. The idea behind the splash screen example is to introduce the user to the application by showing a form with perhaps a logo or colorful graphic. The splash screen should display for a few seconds and then automatically switch to the application's main screen with no intervention from the user.

To build this sample application, perform the following steps: Start a new VB project. Set the following properties of the form: Property Value (Name) frmSplash BorderStyle 0 None

Place an Image control on the form. (Be sure to use an Image, and not a PictureBox.) While the PictureBox is a versatile control, more overhead is involved in using it. If all you want to do is display an image, then use the Image control. The PictureBox can also be used to display an image, but it also enables you to use graphics methods and can also serve as container (similar to a Frame) that lets you house other controls. Since we don't want to do any of that stuff and just want to display an image, we'll stick with the Image control.
Page 31 of 50

Resize the Image control to encompass the size of the form. Name the control imgClouds. Set the Stretch property to True. When the Stretch property is True, the picture you assign to the Image control will automatically expand or contract to conform to the size of the control. When the Stretch property is False, the Image control will automatically resize itself to expand or contract to the size of the picture that is assigned to it. Set the Picture property. When you click the ellipsis button on the Picture property, a dialog box will open to allow you to navigate your system to find a suitable picture file. The main types of files that can be assigned to an Image control are .bmp, .jpg, .ico, and .wmf. Depending on the OS you are using, the clouds.bmp file may or may not be present on your system. If it is, the most likely place it would be is in either the Windows or WINNT directory. If you cannot find "clouds.bmp", simply navigate your system to locate any file of the appropriate type. Once you find your file, click Open on the dialog box. The picture will then fill the Image control.

Place a Label on the form, move it to the center of the form and increase its width to encompass the width of the form. Set the properties of the label as follows: Property Value Alignment 2 - Center BackStyle 0 Transparent Caption My Cool Application Font Arial (Bold Italic, Size 24)

Place a Timer on the form and set its properties as follows: Property Value (Name) tmrSplash Enabled True (the default) Interval 3000 (3 seconds)

At this point, your form should look something like this:

Page 32 of 50

From the VB Project menu, choose Add Form and select the option to add a new form. Name the new form frmMain. For the purpose of this demo, you need not place any controls on this form. Back on frmSplash, code the tmrSplash_Timer event as follows: Private Sub tmrSplash_Timer() tmrSplash.Enabled = False frmMain.Show Unload Me End Sub

Run the project. The splash screen will display for three seconds and then the main form will be displayed. Close frmMain. The Image Control You've already seen in the previous topic that with an Image control, you can set it's Picture property at design time by going to Picture property, clicking the ellipsis (), and selecting a file from the Load Picture dialog box. Recall that the main types of files that can be assigned to an Image control are .bmp,.jpg, .ico, and .wmf. The Image control has a Stretch property, which is set to False by default. When the Stretch property is False, the Image control will automatically resize itself to expand or contract to the size of the picture that is assigned to it. If instead you want the image to fill the specific size that you make the Image control, set the the Stretch property to True, which will cause the picture you assign to the Image control to automatically expand or contract to conform to the size of the control. Depending on the type of image, the image may or may not appear distorted when stretched this is something you need to experiment with.
Page 33 of 50

You can also set the Picture property of an image control in code by using the LoadPicture function, which loads a picture from a file into the control at run-time. The LoadPicture function takes a file name as an argument. Sample syntax is: imgMyPic.Picture = LoadPicture("C:\SomeDirectory\SomeSubDir\MyPic.bmp") "Picture" is the default property of the image control, so the above statement could have been written as: imgMyPic = LoadPicture("C:\SomeDirectory\SomeSubDir\MyPic.bmp") (Note: In my earlier VB programming, I would typically omit the default property of controls; however, I now advocate explicitly coding all properties so I recommend keeping the ".Picture" on there.) Keep in mind the following general points about setting the Picture property of a control using LoadPicture at run-time compared to selecting a file for the control's Picture property at design-time:

When you set the picture at design-time, that picture becomes embedded in your application (it is stored in the .frx file of the form that is using it). Therefore, your program is bigger, but runs faster because the picture is in memory when your program loads. When you use LoadPicture, the program is smaller because the image is not embedded in the application, but resides in a separate file. However, the image processing is slower because the program must access it from disk. To clear the picture from an image control, use the LoadPicture function with an empty set of parentheses: imgMyPic.Picture = LoadPicture() If you have more than one image control on a form, you can copy a picture from one image to another via an assignment statement like this: imgPic1.Picture = imgPic2.Picture - or imgPic1 = imgPic2 A common technique to change an image on a form at various points in the program is to use a number of image controls as a "repository". The images in the "repository" will all have their Visible property set to False. At the desired time, the program will assign one of the images from the "repository" to the image to be displayed. The following sample program demonstrates this technique.

The sample program displays a traffic light that alternates color from green to yellow to red every half of a second. All images used are icons from the folder: Program Files\Microsoft Visual Studio\Common\Graphics\Icons\Traffic.

To build the sample program, use the figure below as a guide to place the indicated controls on the default form and set the properties of the controls to the values indicated in the callouts.
Page 34 of 50

The code for the program is as follows:

Option Explicit

Private mstrCurrColor As String

Private Sub Form_Load() mstrCurrColor = "G" imgLight.Picture = imgGreenLight.Picture End Sub

Private Sub tmrChangeLight_Timer()

If mstrCurrColor = "G" Then imgLight.Picture = imgYellowLight.Picture mstrCurrColor = "Y" ElseIf mstrCurrColor = "Y" Then imgLight.Picture = imgRedLight.Picture
Page 35 of 50

mstrCurrColor = "R" Else imgLight.Picture = imgGreenLight.Picture mstrCurrColor = "G" End If

End Sub

When the program runs, the traffic light will alternate in color between green, yellow, and red at intervals of one half of a second:

Download the VB project code for the example above here.

The PictureBox Control Like the Image control, the PictureBox control can be used to display images. However, the PictureBox can do much more. Like the Frame control, the PictureBox is a "container" control, meaning that other controls can be placed inside it. In addition, the PictureBox can be used to generate run-time graphics and to display text. As a general rule of thumb, if your application requires the special capabilities of the "heavyweight" PictureBox, then use it; but if all you want to do is display an image, then use the "lightweight" Image control. Using Images with the Form

The Form has both a Picture property and an Icon property. The Form's Picture property is used to display an image directly on the form; this can be suitable for displaying a background image. In the screen shot below, the Form's Picture property was set to a file called "Santa Fe Stucco.bmp". The image is displayed
Page 36 of 50

starting in the upper left-hand corner of the form and cannot be moved or resized. If you want to display an image directly on the form like this, and you want the image to fill the entire background of the form, you must make sure the image to be used is the same size or larger than the size you want to make the form. (If the image you want for the background of the form is too small, use an Image control that you set to be the same size as the form with its Stretch property set to True, as was done in the previous topic's sample program with the "clouds.bmp" image.)

Note: To clear the Picture property at design-time, highlight the entry for the Picture property ("(Bitmap)" in this case), and press the Delete key.

Page 37 of 50

The Form's Icon property is used to set the icon that is displayed in the left-hand corner of the Form's title bar. In the screen shot below, the Form's Icon property was set to the SUN.ICO icon from the Program Files\Microsoft Visual Studio\Common\Graphics\Icons\Elementsfolder.

When you compile a VB program, the icon used for the resulting EXE is determined by the setting of the Icon property of the Form you specify on the "Make" tab of the project's properties sheet (accessed from the IDE's Project menu item). As shown below, the icon that will be used for this application's EXE will be the "sun" icon from "Form1". If the project had more than one form, then you could choose which form's icon would be used for the EXE by selecting the appropriate form name from the "Icon:" drop-down box:

Page 38 of 50

The Picture Property of the Command Button

The Command Button control has a Style property, which, when set to 1Graphical, enables you to display a picture on the button via the command button's Picture property. (Also when the Style is set to 1-Graphical, you can change the BackColor of the button, which you cannot do when the Style is set to 0Standard.)

If the command button also has a non-blank value for its Caption property, the text of the caption will appear below the picture. (Note: In VB6, you cannot specify the position (left, right, below) of the picture relative to the caption on the command button: the picture will always appear above the caption. A custom button control would be needed to display the picture to the left or right of the caption on the button.)

The screen shot below shows two command buttons with images (the images shown are from a custom icon set):

Page 39 of 50

The command button also has a DisabledPicture property, which allows you to specify an alternative image to be displayed on the button when the Enabled property is set to False:

If you don't use the DisabledPicture property, the system will "do its best" to render a disabled image based on the original what it comes up with may or may not be acceptable to you:

Another technique used with "picture buttons" is to place only a picture on the button and leave the Caption blank then use an adjacent Label control to describe the function of the button, as shown in the "switchboard" type screen below:

Page 40 of 50

Using Images with Other Controls

Images can be used with many with other controls. In later topics, a set of controls called the Windows Common Controls will be explored. This set of controls comprises the ToolBar, TreeView, ListView, TabStrip, StatusBar, and several others. These controls are used in conjunction with an ImageList control, which serves as a repository for images to be used for items within the controls (i.e. icons for the Toolbar buttons, TreeView nodes, ListView list items, etc.) The screen shot below shows a portion of a screen used by an application that uses a ToolBar, TreeView, and ListView.

Page 41 of 50

Finding Images to Use with Your Applications

Probably the most challenging aspect of incorporating images (particularly icons) into your application is not the actual programming, but simply the search for the "right" icon or image to represent the function or concept to be worked with in your application's user interface.

As mentioned previously, Visual Studio 6/Visual Basic 6 comes with a set of over 900 graphic files (over 500 of which are icons). When Visual Studio 6 or VB 6 is installed, the Graphics folder is NOT installed by default (whoever is installing it must explicitly check the "Graphics" option during the appropriate step of the installation). Assuming that the Graphics are installed, by default they will be placed in the directory structure shown below:

Page 42 of 50

The Icons folder contains 13 subfolders. As a reference, and for convenience, screen shots of the contents of the icon folders are shown below:

Page 43 of 50

Page 44 of 50

Page 45 of 50

Page 46 of 50

Page 47 of 50

Page 48 of 50

Even with all of the icons and other graphic files included with VB, you may not find images that you deem suitable for your application. Not all "categories" of icons that you might expect are present in the included collections, and those that are included would be regarded by some as "dated" (the offering of included icons has not changed since VB 3.0 back in 1995). Fortunately, there are numerous resources on the Internet for icon collections (ranging in price from free to several hundred dollars) as well as resources for working with icons (creating your own and/or modifying existing icons).

Page 49 of 50

Page 50 of 50

S-ar putea să vă placă și