Visual Basic Material
Visual Basic Material
Lesson 1
What Is Visual Basic and Why do I need it? Visual Basic is Easy to learn Programming language. With Visual Basic you can develop Windows based applications and games. Visual Basic is much more easier to learn than other language (like Visual C++), and yet it's powerful programming language. Visual Basic suit more for application developing than for Games developing. You can create sophisticated games using Visual Basic, But If you want to make a really advanced professional game like Quake 2, You may choose other language (like C++), that would be much more harder to program with. However, Visual Basic will be probably powerful enough to suit all your application and games programming needs. The advantages of Visual Basic: 1) It's simple language. Things that may be difficult to program with other language, Can be done in Visual Basic very easily. 2) Because Visual Basic is so popular, There are many good resources (Books, Web sites, News groups and more) that can help you learn the language. You can find the answers to your programming problems much more easily than other programming languages. 3) You can find many tools (Sharewares and Freewares) on the internet that will Spare you some programming time. For example, if you want to ping a user over the internet in your program, Instead of writing the ping function yourself, you can download a control that does it, and use it in your program. Compare to other languages, Visual Basic have the widest variety of tools that you can download on the internet and use in your programs. The disadvantages of Visual Basic: 1) Visual Basic is powerful language, but it's not suit for programming really sophisticated games. 2) It's much more slower than other langauges.
Getting Started Note that all the images in this tutorial taken from Visual Basic version 6.0. If you using other version of Visual Basic, the images that you will see may be a little different. Run the Visual Basic program. The first thing you see is: Figure 1
Here you choose what is the kind of the program you want to create. For creating a simple Visual Basic program, choose the Standard EXE, and press the Open Button. (If Figure 1 is not the first thing you see when you run Visual Basic, choose from the Visual Basic menu File->New Project (Figure 2))
Figure 2
After you've clicked the Open button, you will see: Figure 3
Getting Started (Continue) Look at the form with the title bar Form1. This is how your program will look like. Everything you will place on this form will appear in your program. As you can see, your form is currently empty. You didn't program anything yet, but lets run the program! Click on the Play button in the toolbar (Figure 4) Figure 4
Figure 5
As you can see, the form is empty. You can move the form, minimize and maximize it. To stop the program from running, you can click on the Stop button in the Toolbar (Figure 6), or click the form's X button (Figure 7). It's very recommended that you will always close your programs using the form's X button instead of the Visual Basic Stop button. It's like shutting Windows From the Start button, instead of Pressing the Power button. Figure 6
Figure 7
Every component (form is component for example) has properties, that determine its look and its functioning. Properties can be the component color, width, height and more. To see the form properties, select from the menu View->Properties Window (Figure 8). Figure 8
Figure 9
In the red circle you can see the component name: These are the properties of a Form, and the form's name is Form1. The column marked by the blue circle contains the form's properties names: The form has Name property, Appearance property AutoRedraw property, and more. The column marked by the black circle contains the form's properties values: The form's Name is Form1, The form's Appearance property is 1 - 3D, and so on. You can change the form's properties. For example, lets change the form's Caption property. What is the Caption property? The Caption is the text that appears on the Form's title bar. Right now the text that appears on the form's title bar is Form1 (Figure 5). To change the Caption property, simply click on the Caption property in the form's properties names column (Figure 10).
Figure 10
As you see, the current Caption is Form1. Delete the "Form1" text and type instead of it "Hello" (Figure 11). Figure 11
Now run the program using the Play button (Figure 4). You will see that the text on the form's Title bar is Hello (Figure 12).
Figure 12
Try to change others properties: Change the form's BackColor property to change the form's background color, Change the Icon property to change the icon that appears on the form's title bar. You can try and change every property, and in this way learn what does it do. Adding Controls to the Form There are many controls you can use with your program: Buttons, Text Boxes, Pictures, Scroll Bars and more. You can see all these controls in the Toolbox. To see the Toolbox, Select from the menu View->Toolbox (Figure 13). Figure 1
Now lets add a button to your form. Buttons in Visual Basic called "Command Buttons". To add a button, click on the Command Button icon in the Toolbox (Figure 15). Figure 15
As results, the Command Button icon will look pressed (Figure 16). Figure 16
Now click on the form with the left mouse button, and hold the button down while moving the cursor. You will see a rectangle. Release the mouse button, and in the place of the rectangle you will see a button (Figure 17). Figure 17
Changing the button's Properties Now you have a button on your form. You can change its location by dragging it, and change its size by dragging the Blue Hot Spots that found on each one of its conrners. Run the program by clicking the Play button. You can see that you have a button on your form, that you can click on it, But it still doesn't do anything. To see the Command Button's Properties window, click on it with the right mouse button and select Properties for the pop-up menu (Figure 18). Figure 18
As you can see, In the top of the properties window, right under the title bar, appears "Command1 CommandButton". Command1 - because it's the name of this specific Command Button (look at the name property). CommandButton - because this is this component type. Note that two components can't have the same name. If you will add another Command Button to your form, its name will be "Command2" by default. If you want you can change the Name of any component, by simply
Now lets change the Command Button's Caption property. The caption property is the text that appears on the Command Button. Change the Caption property to "Click Here", and you will see that "Click Here" appears on your Command Button. Change the Command Button's BackColor property to blue (or other color). The change won't take affect, untill you will set the Command Button's Style property to 1 -Graphical. You can now play a little bit with the Command Button's properties, this is the best way to learn what every property does. You can also add other controls from the Toolbox to your form, And play around with their properties. Learning about Events
Visual Basic is "Event Driven" language. What does it mean? Everything that happening, launch an event. You've moved the mouse? The "MouseMove" event has been launched. You've pressed a key? The "KeyPress" event has been launched. You can program the events. When the mouse moves, you can change the Form's color (for example), and when a key is pressed, You can play a MP3 file. To start programming the events, double click on the form. You will see the "Code Window" (Figure 20). Figure 20
The Code Window opened with the Form_Load event. The Form_Load event occurs when the form is loaded, and this happening
when you start the program. So the code that you will enter to the Form_Load event will be launched when the program is being started. The code that belongs to the Form_Load event should be placed between Private Sub Form_Load() and End Sub The Form_Load event should look like this: Private Sub Form_Load() (The beginning of the Form_Load event) This is the code that belongs to the Form_Load event End Sub (The end of the Form_Load event) Learning about Events (Continue) Lets program the Form_Load event. "MsgBox" is Visual Basic command that launch a message box. for example, the line: MsgBox "Hello" Will launch a message box with the text "Hello". Insert the line Figure 21 MsgBox "Hello" to the Form_Load event (Figure 21).
Now run your program using the Play button. When the program is started, a message box with the text "Hello" is appear (Figure 22). Figure 22
More Events The Form has more events besides the Form_Load event. How can you find them? Click on the Drop-Down List that found in the upper left corner of the Code Window, where appears right now the text "Form" (Figure 23). Figure 23
You will see a list of the components that found in your program. You have 1 command button with the name "Command1" and 1 Form. Here you select which component's event you want to program. We want to program a form's event, so select "Form" from the list (Figure 23). Which events the form has? Click on the Drop-Down List that found in the upper right corner of the Code Window, where appears right now the text "Load" (Figure 24). Figure 24
You will see the complete list of the form's events: Load, LostFocus, MouseDown, MouseMove and more. Lets program the Form_Unload event. Select "Unload" from the form's events list. The Form_Unload event occurs when the form is being unloaded, and this happening when you close the program (Using the form's X button (Figure 7)). So the code that you will write in the Form_Unload event will be launched when you close the program. Insert the following line to the Form_Unload event: MsgBox "GoodBye" After you've inserted this line to your Form_Unload event, the Form_Unload event should look like this: Private Sub Form_Unload(Cancel As Integer) MsgBox "GoodBye" End Sub Run the program. When the form is being loaded at the very start, The Form_Load event is being executed and a message box with "Hello" text is popping. When you close the program by clicking the form's X button, the Form_Unload event is being executed and a message box with "GoodBye" text is popping. The Command Button's Events Now lets program some of the Command Button's events. Select "Command1" from the components list (Figure 23). Check which events the Command Button has by clicking the Events list (Figure 24). We want to execute a code when the user is clicking on the button, So lets program the Command Button's Click event.
Select "Click" from the Events list. Insert the following line to the Click event: MsgBox "You have Clicked on the button!"
After you inserted this line to the Click event the Click event should look like this: Private Sub Command1_Click() MsgBox "You have Clicked on the button!" End Sub As you can see, the Command Button's Click event called "Command1_Click", because the name of the specific Command Button that we program its Click event is "Command1". If we had program the Click event of a Command Button with the name "BlahBlah7", the Click event would be called "BlahBlah7_Click". Every component has its own unique events, therefore if you had 5 Command Buttons on your form, every one of them has its own unique Click event. Run the program, and click the button. When you clicking the Command Button with the name "Command1", The Command1_Click event is being executed, and a message box with the text "You have Clicked on the button!" is popping.
The Command Button's Events (Continue) To learn about more events, we will use the "Print" command. The "Print" command simply writing a text on the form. For example, the following line: Print "Hello" Will write "Hello" on the form (Figure 25) Figure 25
Add another Command Button to your form. The New Command Button's name is "Command2" by default (Figure 26) Figure 26
Now, rewrite the Command1 Click event and insert the following line to it: Print "This is Command1" Select "Command2" (This is the name of the second Command Button) from the Components list (Figure 23), And select "Click" from the Command2 events List. Enter the following line to the Command2_Click event: Print "This is Command2" After you've done so, your code should look like this:
Private Sub Command1_Click() Print "This is Command1" End Sub Private Sub Command2_Click() Print "This is Command2" End Sub
Run the program. When you are clicking on Command1 Button, the text "This is Command1" appears on the form, and when you are clicking on Command2 Button, the text "This is Command2" appears on the form. Proceed to Lesson 2 to learn about variables.
Lesson 2
Learning about Variables
Using Variables is one of the most basic and important subjects in programming, so this lesson is very important. Variables are destined to save data. You can save in variable Text or number. For example, you can have one variable that holds the Text "Hello and Goodbye", and have another variable that holds the number 623882 You can think about variables as a cabinet's drawers. Every drawer has a sticker on it with its unique name. You can put in each one of the drawers one number or one text String. During your program, you can open the drawer with the sticker "TheUserName" and get the text string that found inside the drawer. You can also delete the text string that found inside the drawer and put instead of it other text string. Right now, we are going learn about 2 variable types. The first type called Integer. Integer variable can store an Integer number (round number without any fraction) between -32,768 to 32,767. You can store in Integer variable the number 0 or the number 375 or the number -46, but you can't store the number 4.5 (Because of the .5) or the number 100,000 (Because It's bigger than 32767) or the number -50,042 (Because it's smaller than -32,768) The second type called String. You can store in String variable any text that you want. For example "Hello" or "abcDDefGhIjk123456 blah blah %$#@!??? Working With Integers The process of creating variable called "Declaring" To Declare (=create) Integer variable simply write: Dim MyTest As Integer What does the line above do? It creates an Integer variable with the name MyTest. Dim = Declare MyTest = the name of the new variable As Integer = The new variable type will be Integer. Now you can put a number inside this variable. You can do that by simple write:
Blah!"
MyTest = 10 The line above will insert the number 10 into the MyTest variable. Now the MyTest variable stores the Number 10, but how can you access this value from your program? You can do that using the variable name. Example: Print MyTest The line above will write 10 on the form. Pay attention to the differents between Print MyTest and Print "MyTest" Where you putting a text inside quotes (Like in the bottom line), Visual Basic treat it as a Text, and will print it As-Is. The Print "MyTest" Line will print MyTest on the form. Where you putting a text Without quotes (Like in the upper line), Visual Basic treat it as a variable name, and will print the value that found in the variable. The Print MyTest Line will print the value that found in the MyTest variable, therefore it will print 10 on the form. Working With Integers (Continue) Question: What will be printed on the form after executing the following code: Dim Blah As Integer Print Blah Blah = 10 Blah = 20 Print Blah Blah = 30 Print "Blah" Print Blah After you've thinking about the answer, you can check it by inserting the code above into a Command Button's Click event, and press the button at run-time. Anyway, the Answer can be found on the next page...
Blah 30 Why is that? Lets pass over the code line after line: Dim Blah As Integer A new Integer with the name Blah has been declared Print Blah Will print the Value that found in the Blah variable. But there is nothing in the Blah variable! The Blah variable has just been declared, and we didn't put inside it any value yet. The default value of any integer variable is 0. When you write : Dim Blah As Integer It's like you've written: Dim Blah As Integer Blah = 0 So it will print the value that found right now in the Blah variable - 0 Blah = 10 Now the Blah variable holds the number 10 Blah = 20 Now the Blah variable holds the number 20 What's happened to the 10 that was inside it? It has been deleted! A variable can holds only one value, and when you put in it a value, the old value is being immediately deleted. So what is the differents between Blah = 20 and Blah = 10 Blah = 20 ? There is no differents! In both cases the Blah variable will hold the number 20 Print Blah Will print the value that found right now in the Blah variable - 20 Blah = 30
Now the Blah variable holds the number 30 Print "Blah" Will print the Text that found between the quotes - Blah Print Blah Will print the value that found right now in the Blah variable - 30 Working With Integers (Continue) Question: What will be printed on the form after executing the following code: Dim Blah As Integer Blah = 2 Print 2 + 3 Print "2 + 3" Print Blah + 3 Print Blah Blah = Blah + 1 Print Blah Blah = Blah + Blah Print Blah The Answer can be found in the next page... Working With Integers (Continue) Answer: 5 2+3 5 2 3 6 Why is that? Lets pass over the code line after line: Dim Blah As Integer A new Integer with the name Blah has been declared Blah = 2 Now Blah holds the value 2 Print 2 + 3 When you execute command (the Print command in the case) on expression, Visual Basic will evaluate the expression first, and then will execute the command on the evaluation result. In this case we execute the command Print on the expression 2 + 3.
The expression will be evaluated: 2 + 3 = 5. The evaluation result is 5, and then Visual Basic will execute the command Print 5 So in other words, Print 2 + 3 is equivalent to Print 5 after executing the Command Print 5 , 5 is been printed on the form. Print "2 + 3" As I said before, Everything that found inside quotes is being treated as a string. So the string 2 + 3 will be printed on the form. Print 2 + 3 will print the value of the expression 2 + 3, Print "2 + 3" will print the text string 2 + 3 Print Blah + 3 Now the expression is Blah + 3. when a variable is found inside expression, it's being replaced with its value. In this case the value of the variable Blah is 2. So the Blah in the expression is being replaced with 2. After the replacement the new command is Print 2 + 3 As we saw earlier, after executing this command the value 5 will be printed on the form. Print Blah Will replace the Blah with its value. Because the Blah value is 2, After the replacement the new command will be Print 2 After executing this command, the value 2 will be printed on the form. Blah = Blah + 1 The line above simply says: Put in the Blah variable, the value of the expression Blah + 1 The computer is first evaluate the expression Blah + 1 Blah is being replaced with its value: 2. After the replacement the computer evaluates the expression 2 + 1. The expression value is 3. So now, after the "Blah + 1" expression evaluation, the command is: Blah = 3 As you know by now, this command will put the value 3 in the Blah variable. Summary: After executing the command Blah = Blah + 1, the value 3 will be inserted into the Blah variable. Print Blah Will replace the Blah variable with its value: 3. So the command that will be eventually executed is Print 3 Blah = Blah + Blah Will Put in the Blah variable, the value of the expression Blah + Blah The computer is first evaluate the expression Blah + Blah Blah is being replaced with its value: 3. After the replacement the computer evaluates the expression 3 + 3. The expression value is 6.
So now, after the "Blah + Blah" expression evaluation, the command is: Blah = 6 After executing the command Blah = 6, the value 6 is being inserted into the Blah variable. Print Blah Will replace the Blah variable with its value: 6. So the command that will be eventually executed is Print 6 More Complicated Expressions You can use the following operators in expressions: + Plus - Minus * Multiply / Division ( Openning parenthesis ) Closing parenthesis ^ Power
For example, this is a valid expression: (Blah + 5) * MySecondVariable - (4 + 10 / Blah) The order of the operators are like in math: First "(" and ")" , then "^", then "*" and "/", and at last "+" and "-" For example: 2 + 3 * 4 is equal to 14 (2 + 3) * 4 is equal to 20 More Variable Types What will be printed on the form after executing the following code? Dim ABC As Integer ABC = 4.8 Print ABC Answer: The Integer variable can't store a number with fraction, So the computer will round the 4.8 to 5, and will Insert 5 to the ABC variable. So the Command Print ABC will print 5 on the form. So how can you store a number with fraction in a variable? For this purpose you have other variable types that can store round numbers like the Integer type, and in addition can store numbers with fractions. The Variable types list:
Byte - Can store only Integer numbers between 0 to 255 Integer - Can store only Integer numbers between -32,768 to 32,767 Long - Can store only Integer numbers between -2,147,483,648 to 2,147,483,647 Single - Can store Non-Integer (numbers with fractions) Numbers between -3.402823E38 to -1.401298E-45 for negative values, and 1.401298E-45 to 3.402823E38 for positive values. Double - Can store Non-Integer Numbers between -1.79769313486231E308 to -4.94065645841247E-324 for negative values, and 4.94065645841247E-324 to 1.79769313486232E308 for positive values Why would I use Byte variable that can store Integer numbers between 0 to 255, while I can use Integer variable that can store numbers between -32,768 to 32,767? The Answer is: Because the Byte variable is taking less memory. So if you have variable that will not store numbers greater than 255 or less than 0, declare it as Byte variable and save a little amount of memory. If you need to store Non-Integer numbers in variable, declare it as Single or as Double. The Declaring command is very simple: Dim Abc As Double Dim Blah As Single Dim Popeye As Byte And so on. Working With Strings String variables are meant to store Text. When you assign a text to a String variable, you must put the text inside quotes. For example: Dim Abc As String Abc = "Good Morning" Question: What will be printed on the form after executing the following code? Dim kuku As String kuku = "Hello!!!" Print "kuku" Print kuku
Answer: kuku Hello!!! Why is that? Lets pass over the code line after line: Dim kuku As String Will create a new String variable kuku = "Hello!!!" Now the kuku variable holds the text Hello!!! Print "kuku" Everything that found inside quotes is being treated as text String, So it will print kuku on the form. The computer Is NOT associate the text "kuku" with the variable kuku, because of the quotes. Print kuku Will replace the kuku with its value (Hello!!!), and after the replacement will execute the new command Print "Hello!!!" Working With Strings (Continue) You can join two Strings together using the "+" operator. Example: Dim gogo As String Dim popo As String gogo = "Hello" popo = "world" gogo = gogo + " !!! " + popo Print gogo The code below will print Hello !!! world on the form. The expression gogo + " !!! " + popo is equal to Hello + " !!! " + world and that's equal to "Hello !!! world" So eventually, the command that will be executed is gogo = "Hello !!! world" Scope of Variables Insert two Command Buttons to your form (with the names Command1 and Command2), and Add the following code to your program: Private Sub Command1_Click() Dim gogo As Integer gogo = 100 End Sub Private Sub Command2_Click() MsgBox gogo End Sub
Run the program, and click on the Command1 button. the code that found in the Command1_Click event will be executed. The gogo variable will be declared, and it will store the value 10. Now press on the Command2 button. In result, the MsgBox gogo Line will be executed. But instead of displaying the value of the gogo variable (100), It shows nothing, like if the gogo variable hasn't been declared at all! The reason for all of this, is the scope of the variable. Every variable that been declared, "Exist" only in the Sub or function that he was declared in. What is Sub? (We will learn about functions later) Sub is a Block of code that starts with Sub and ends with End Sub Every event is a sub, because it begins with Sub and ends with End Sub For Example: Private Sub Command1_Click() MsgBox "Hello" End Sub Every line of code that found between the Sub Command1_Click() and the End Sub is belong to the sub Command1_Click() So because we've declared the gogo variable in the Commad1_Click event, it's declared only within the sub, and it's not declared in the Command2_Click event. So if you want that a specific variable will be "exist" in your whole program, no matter from which sub you call it, what can you do? The Answer is in the next page... Scope of Variables (Continue) As you saw in the previous page, If you declare variable in a sub, it exist only within the sub. To declare variable that will be exist in all subs, you have to declare it in the "Declarations area" of your code. Choose "(General)" From the components List in the code window (Figure 1). Figure 1
Put the gogo declaration statement in the "Declarations area". Simply write: Dim gogo As Integer And delete the old statement that found in the Command1_Click event. After you've done so, your code should look like this: Dim gogo As Integer Private Sub Command1_Click() gogo = 100 End Sub Private Sub Command2_Click() MsgBox gogo End Sub Now the gogo variable is being declared in the Declarations area of your code, and should be available from every part of your code. Lets check it out: Run the program. The gogo variable is being declared immediately when the program is being started. Press the Command2 Button. A message box with the number 0 is popping. It is because the gogo variable has been declared, but we didn't assign any value to it yet, so right now its value is the default value - 0. Press the Command1 Button. The value 100 is being assigned to the gogo variable. Press the Command2 Button - a message box with the value 100 is popping.
Choosing A Valid Name For Variable When declaring on variable, you choose its name. For example: Dim Tuti As Integer The example above will set the variable name to be "Tuti". The names you choose for your variables don't have to have any meaning, but still there are some limitations about the names you can call your variables. The Rules: 1)The only characters that can appear in the name are letters, numbers and the character _ (the underscore character) You can't use other characters like: ` ! @ # % ^ & * ( ) Therefore, the following names are NOT valid: AB!, BB$, tot#o 2)The Name Must begin with a letter: You can't use the names: 2abc, 3, 2345, _aba 3)You can't use space in the variable's name. Therefore, the following names are NOT valid: A B, hello world 4)You can't call your variable with a name that is a Visual Basic Command or Function (these names are been called "saved names"). For example you can't use the name Print, because there is command in Visual Basic that called Print (which we used pretty much in this tutorial). You can know easily if a name is a saved name by typing it anywhere in your code. All the saved names are being painted with blue color. Few examples for saved names: Print, Sub, End, MsgBox Examples for valid names: a, A, AaAaA, aBhguKJhUJYf, abc123, abc123abc123, hello_world123 There is much more to learn about variables, like constants, booleans, arrays and more. What you've learnt by now is necessary for continuing with the next lessons. More advanced variables subjects will appear during the next lessons. Go to Lesson 3 to learn more about Events and properties
Lesson 3
The Command Button's KeyPress, KeyDown and KeyUp Events The events that will be mentioned in the following pages are commonly used, and without learning about them you really can't go anywhere in Visual Basic programming. To try these examples, start a new project (as being taught in Lesson 1). Add 1 Command Button to your form. The Command Button is called by default Command1. Copy the following code to the code window (you can copy and paste it using Ctrl + C for copying and Ctrl + V for pasting): Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer) Print "KeyDown" End Sub Private Sub Command1_KeyPress(KeyAscii As Integer) Print "KeyPress" End Sub Private Sub Command1_KeyUp(KeyCode As Integer, Shift As Integer) Print "KeyUp" End Sub
When the Command Button's KeyDown event will be executed, "KeyDown" will be printed on the form, When the Command Button's KeyPress event will be executed, "KeyPress" will be printed on the form, and when the Command Button's KeyUp event will be executed, "KeyUp" will be printed on the form. Run the program, and click the button with the mouse. Nothing has happened. It's because the KeyDown, Key_Press, and KeyUp events are being executed Only when you press a key on the keyboard. Now press any key on the keyboard, hold it down for few seconds, and then release it. Your form will look like this:
Figure 1
Lets see: The first event that been executed is the KeyDown event, because "KeyDown" was the first text that been printed on the form. The second event was KeyPress, and then again KeyDown. After every KeyDown event that been executed, a KeyPress event had been executed. We learnt that when a key is being holded down, the KeyDown and the KeyPress events are being executed in this order over and over again, until the key is up again. When you release the key, the KeyUp event is being executed once. Learning about Parameters Parameters are variables that being passed to a Sub. Look at the first line of the Command Button's Click event: Private Sub Command1_Click() And at the first line of the Command Button's KeyPress event: Private Sub Command1_KeyPress(KeyAscii As Integer) The Click event's first line is ended with empty parentheses () and the KeyPress event's first line is ended with (KeyAscii As Integer) What is the ?
(KeyAscii As Integer)
It's a parameter that been passed to the KeyPress event. This parameter is an Integer variable with the name KeyAscii. Like if you've declared Dim KeyAscii As Integer Why do we need this variable? Because its value is very useful. The KeyPress event is being executed when the user press a key, and This variable holds the Ascii value of the key that been pressed. With This Ascii value you can know on which key the user has pressed. For example, the Ascii value of the "A" character is 65. If the user has pressed the key "A" on the keyboard, The KeyAscii parameter value will be 65. Lets see an example. Insert the following line to the Command1 KeyPress event: Private Sub Command1_KeyPress(KeyAscii As Integer) Print KeyAscii End Sub
Run the program and press several keys. You will see the Ascii value of every key you're pressing. Notice that the KeyAscii values of "A" and "a" are differents. Every characters has its own KeyAscii value, and 2 characters that are the same letter, but have different case, have different KeyAscii value. More About Ascii How can I know what is the Ascii value of a specific character? Use the Asc command. For example, the following line: Print Asc("b") Will print on the form the Ascii value of the character "b". How can I know which character's Ascii value is 98? Use the Chr command. For example, the following line: Print Chr(98) Will print on the form the character that its Ascii value is 98.
Learning about Parameters (Continue) Look at the first line of the Command Button's KeyDown Event: Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer) As you can see, the KeyDown event gets two parameters: The KeyCode parameter, and the Shift parameter, both are Integer type. Every Sub can get no parameters (like the Click event), can get one parameter (like the KeyPress event) or can get more than one parameter. If a sub is getting more than one parameter, the parameters have to be separated with commas. For example: Private Sub MySubName (Parameter1 As String, Parameter2 As Integer, Parameter3 As String) Lets check out the KeyDown event's parameters. The first is KeyCode, and it holds the KeyCode value of the pressed key. The KeyCode value is usually different from the Ascii Value. The different between KeyCode and Ascii, is that every character has Ascii value (for example G, @, |, =, and more) but there are some keys that don't represent any character, for example: Alt, F4, Ctrl, The left arrow key. These keys don't have Ascii value, but they have KeyCode value. For example, the KeyCode value of the Ctrl Key is 17. Ascii represent characters, while KeyCode represent Keyboard's keys. Because of that, the characters "a" and "A" have different Ascii value, but they have the same KeyCode value, because the same key is typing "a" and "A". The second parameter is Shift, and its value helps you to determine if the user has pressed the Shift, Ctrl or Alt keys. The Shift holds the value 1 if the user has pressed the Shift key, the value 2 if the user has pressed the Ctrl Key, and the value 4 if the user has pressed the Alt Key. If the user has pressed the Alt key and the Shift key together, the Shift value will be 4 (for the Alt key) + 1 (for the Shift key) = 5 Examples: If the user has pressed the "A" key, The KeyCode parameter will hold the number 65, and
the Shift parameter will hold the value 0. If the user has pressed Shift and "A" together, The KeyCode parameter will hold the number 65, and the Shift parameter will hold the value 1. The KeyUp event's parameters are the same as the KeyDown event's parameters.
Lets check out these events parameters. Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) Each one of these events gets the same parameters: Button, Shift, X and Y. The Shift parameter is the same as the KeyDown event's Shift paramater. For example, if you'll press the Shift button while clicking the mouse, the Shift value will be 1. The Button parameter value is 1 if you've clicked the left mouse button, and 2 if you've clicked the right one. The X and Y parameters are the X and Y coordinates of the mouse cursor, relative to the upper left button corner. The coordinates of the upper left button corner are (0, 0) The coordinates of the Bottom Right button corner are (Button Width, Button Height) You can try a little example. Put the following line in the Command Button's MouseMove event: Print X, Y This line will print the X coordinate, and next to it the Y coordinates (For example, the line: Print "Hello", "World" will print: Hello World).
Additional Command Button's Properties Add 1 Command Button to your form, and change the following properties to see what they do. Caption - the text that appear on the button Font - The Caption's font (Figure 2).
Figure 2
ToolTipText - Insert into this property the text that will appear when the mouse is stand still on the button (Figure 3). Figure 3
Enabled - Setting this property to "False" will make the button be gray, and the user will no be able to press on it (Figure 4). Figure 4
BackColor - This is the background color of the button (Figure 5). This property will take affect only after you will set the Button's Style property to 1 - Graphical Figure 5
Picture - The Picture that appear on the button (Figure 6). This property and all the following Picture related properties will take affect only after you will set the Button's Style property to 1 - Graphical Figure 6
DisabledPicture - The Picture that will appear on the button when it disabled (When the Enabled property is "False", like in Figure 4). DownPicture - The Picture that will appear on the button when the button is being pressed. Visible - If you will set this property to "False", the Button will not appear on your form at run-time. MousePointer - Choose here the mouse pointer (Arrow, Hourglass, and more) when it will be over the button.
If you will set the property to be 99-Custom, The mouse pointer will be the icon that you will select in the MouseIcon property. Left - The Button X coordinate, relative to the form left border. Top - The Button Y coordinate, relative to the form Top border. Width - The Button width. Height - The Button height. Additional Form's Properties The Form has many of the Command Button's properties (MousePointer, BackColor, Visible and more). He also has additional properties: Caption - The text that appear in the Form's title bar, and in the taskbar. Icon - The Icon that appear in the form's title bar (Figure 7) and in the Task bar (Figure 8). Figure 7
Figure 8
ControlBox - Set this property to "False" to remove the title bar's Close, Minimize and Maximize buttons (Figure 9). Figure 9
MaxButton - Set this property to "False" to disable The title bar Maximize Button. MinButton - Set this property to "False" to disable The title bar Minimize Button. ShowInTaskbar - Setting this property to "False" will cause the form not showing in the task bar. WindowState - The initial appearance style of the form: Minimized, Maximized, or normal.
The Form's KeyPreview Property To understand this property, lets look on the following example: Start new project, and add 1 Command Button (named Command1) to your form. verify that the Form's KeyPreview property is set to "False". Add the following code to your program: Private Sub Command1_KeyPress(KeyAscii As Integer) Print "Button Pressed" End Sub Private Sub Form_KeyPress(KeyAscii As Integer) Print "Form Pressed" End Sub
The code above will print "Button Pressed" on the form when the Command Button's KeyPress event will be executed, and print "Form Pressed" when the Form's KeyPress event will be executed. Run the program and press any key on the keyboard. "Button Pressed" is appearing on the form, but
"Form Pressed" isn't appearing. The Form's KeyPress event hasn't been executed. When the KeyPreview property is "False", if any control is found on the form (the command button in this case), It will get all the Key events (KeyPress, KeyDown and KeyUp) instead of the form. To allow the Form's Key events be executed, set the KeyPreview property to "True". Lets try it. Set the KeyPreview property to "True", run the program again and press any key. The Form's KeyPress event has been executed, in addition to the Button's KeyPress event that been executed too. Notice That the form's KeyPress event executed before the Button's event.
Setting Properties At Run-Time By now you know how to set a component property before running your program (=at "Design Time"), Now we will learn how to do that during program's Run-Time. To change a property, use the following syntax: TheControlName.ThePropertyName = TheNewPropertyValue For example, suppose we have Command Button With the name "Command1", and we want to set its Caption property to be "Hello". To do that, we will use the following code: Command1.Caption = "Hello" To test it, simply copy the line above to your Command1 Click event, run the program and click the button at run-time. Note that the Hello is inside quotes because it's a String. You can assign a variable value to a property: Dim MyVar As String MyVar = "Hello" Command1.Caption = MyVar This code will do exactly the same as the code line above it. Note that MyVar is without quotes, because it's variable.
And how do you set a Form caption property at run-time? exactly the same: Form1.Caption = "Hello" Setting Properties At Run-Time (Continue) Not all the properties get text values. For example, Visible property can be "True" or "False" False and True are not text strings, but Visual Basic commonly used values that called "Boolean" Therefore, when you assign these values to property, You don't have to use the quotes, For example: Command1.Visible = False Form1.Enabled = True Some of the properties values has the following syntax: Number - String For example, the Command Button's Style property can get 2 values: 0 - Standard 1 - Graphical To set these properties value, omit the string. For example: Command1.Style = 1 Form1.WindowState = 2 Some properties represent graphics, for example The Picture property. To set these properties at run-time, use the LoadPicture Command. The example below will load the ICO file "d:\games\toto.ico" to the Picture property of Command Button with the name "MyButton" MyButton.Picture = LoadPicture("d:\games\toto.ico") Setting the BackColor Property You can set the BackColor property at run-time in 2 ways. Way 1: Using the Color's numeric value Every color has numeric value. You can simply assign this value to the BackColor property. For example, The numeric value of the red color is &H000000FF&
If you want to set the Form BackColor property to red, use the following code: Command1.BackColor = &H000000FF& You can find what is the numeric value of every color by making the following simple steps: Click on the BackColor property arrow button in the properties window (Figure 10). Figure 10
The color value will be displayed in the BackColor Property cell (Figure 13). Figure 13
And once again, if you setting a Command Button's color, don't forget to set its Style property to 1 - Graphical. To learn the second way, you'll have to learn a little bit about Constants. All of this in the next page... Setting the BackColor Property (Continue) Way 2: Using the Colors Constants First of all, what is Constant? Constant is a variable that its value can not be changed. Constant holds a common used value. For example, the Constant vbRed holds the value of the red color - &H000000FF& Instead of writing in your code: Command1.BackColor = &H000000FF& You can write: Command1.BackColor = vbRed The 2 statements above are identical, because vbRed = &H000000FF& Where are these constants came from? Visual Basic automatic declare them when the program starts.
Imagine it like as the following code is automatic being entered to your program: Dim vbRed As Long vbRed = &H000000FF& Dim vbBlue As Long vbBlue = &H00FF0000& And so on... But with one exception: You can't change the constants value. For example, the following code is NOT allowed: vbBlue = 5 There are more Color constants, a partial list: vbRed, vbBlue, vbBlack, vbGreen, vbWhite, vbYellow You can declare your own constants. The constant declaration syntax: Const MyVariableName = MyVariableValue For example, the following code will declare a const variable with the name Piano and the (const) value "abcdef" Const Piano = "abcdef" After this declaration, the Print Piano code line will print abcde on the form. In addition, the following code line will not be allowed: Piano = "gggg" Because it's been declared as a Const, and Const value can not be changed. To learn more advanced programming techniques like conditional statements, go to the Conditional Statements Tutorial.
Will print "False" on the form. The value of the boolean expression 3 > 4 is "False", because 3 is not greater than 4. The following code: Dim ABC As Boolean ABC = ("abf" = "abf") Print ABC Will print "True" on the form. The value of the boolean expression "abf" = "abf" is "True", because "abf" is equal to "abf" The following code: Dim ABC As Boolean Dim A As Integer Dim B As Integer A = 1 B = 2 ABC = (A + 1 = B) Print ABC Will print "True" on the form, because the value of the boolean expression (A + 1 = B) is "True". In Boolean expressions you can use the following signs: = Equal to <> Not Equal to > Greater than < Smaller than >= Greater than or Equal to <= Smaller than or Equal to
InputBox In the next examples we want to receive a value from the user when the program is running. To do so we will use the InputBox command. The InputBox command syntax is: VariableName = InputBox ("Text to Display") After executing this command, the variable will get the value that the user has entered.
Example: Put 1 Command button on your form and enter the following code to its click event: Dim Elvis As String Elvis = InputBox("Please Enter your name") Print Elvis Run the program and click the button. A Message Box is appearing with the text "Please Enter your name" (Figure 1). Figure 1
Type your name in the text box, and press OK. Your name will be printed on the form. Conditional Statements The syntax of the conditional statement: If (boolean expression) Then The code to execute if the boolean expression is equal to True Else The code to execute if the boolean expression is equal to False End If Lets make a password protected program. We want to prompt the user to enter the password at the very start of the program, so put the following code in the Form_Load event: Dim Password As String Password = InputBox("Please enter the password") If (Password = "let me in") Then MsgBox "The Password is correct!"
Else MsgBox "Incorrect Password!" End If Run the program. An InputBox is appearing. Type "let me in" (without the quotes) in the InputBox. Note that the text is case sensitive, and if you will type "LET ME IN" you will get a message box with the text "Incorrect Password!". Lets understand how this code works: The boolean expression (Password = "let me in") value is True ONLY if the Password variable value is "let me in". If this boolean expression's value is True, the code that will be executed is the code that located between the Then and the Else (MsgBox "The Password is correct!") If this boolean expression's value is False, and this happens when the Password variable value is NOT "let me in", the code that will be executed is the code that located between the Else and the End If (MsgBox "Incorrect Password!") If you enter a wrong password, a message box is appearing, but the program is continue running. To end the program, use the command End . This command is simply shut down the program. Put the End command in the "Else Section": Dim Password As String Password = InputBox("Please enter the password") If (Password = "let me in") Then MsgBox "The Password is correct!" Else MsgBox "Incorrect Password!" End End If Using "And" and "Or" In Boolean Expressions We can use "And" and "Or" operators to make more complicated boolean expression. In the last example we used the boolean expression Password = "let me in". This boolean expression is "True" if the Password is "let me in", and "False"
If the Password is not. How can we make a boolean expression that will be "True" if the Password is "let me in" or "sam sent me", and if the Password is other than the two above, the boolean expression will be "False"? To create this boolean expression we will use the "Or" operator: (Password = "let me in") Or (Password = "sam sent me") Put the following code in your Form_Load event: Dim Password As String Password = InputBox("Please enter the password") If (Password = "let me in") Or (Password = "sam sent me") Then MsgBox "The Password is correct!" Else MsgBox "Incorrect Password!" End End If Run the program. If you'll type "let me in" or if you'll type "sam sent me" the password will be correct. If you'll type any other text the program will shut down. The "Or" is operator, the same as "+" is operator. How the "+" operator works we already know: 5 + 6 = 11 But how the "Or" Operator works? The "+" operator is being executed on numbers: Number + Other Number = The sum of both numbers. The "Or" operator is being executed on "True" or "False": False Or True = True True Or False = True True Or True = True False Or False = False The 4 examples above are the only options of using the "Or" operator. Lets see what effect has the "Or" operator on the boolean expression we used: (Password = "let me in") Or (Password = "sam sent me") First, the left and right boolean expressions are being evaluated (Figure 2).
For example, if the Password is "let me in" then (Password = "let me in") is True and (Password = "sam sent me") is False. Then the boolean expression is look like this: (True) Or (False) As we saw in the 4 examples above, True Or False = True So the final result of the expression is True (Figure 2). Figure 2 (Password = "let me in") True Or Or True (Password = "sam sent me") False
This boolean expression will be True if the password is "let me in" because True Or False = True, the expression will be True if the password is "sam sent me" because False Or True = True, the expression will be False if the password is NOT "let me in" and NOT "sam sent me" because False Or False = False. Using "And" and "Or" In Boolean Expressions (Continue) The "And" operator is similar to the "Or" operator, except it has different Effects on boolean expressions: True And True = True True And False = False False And True = False False And False = False When using the "And" operator, the expression will be True only if both boolean expressions are True. For example, copy the following code to your Form_Load event: Dim UserName As String Dim Password As String UserName = InputBox("Please enter the user name") Password = InputBox("Please enter the password") If (Password = "let me in") And (UserName = "elvis") Then MsgBox "The login is correct!" Else MsgBox "Incorrect Login!"
End End If This code will pop up two InputBoxes. The first will ask you to enter the user name, and the second will ask you to enter the password. The login will be correct only if both user name and password are correct. The boolean expression (Password = "let me in") And (UserName = "elvis") is True only if (Password = "let me in") is True, and (UserName = "elvis") is True, because True And True = True, and any other combination is equal to False. Using The "Not" Operator The "Not" operator has very simple function: Not True = False Not False = True Before we continue, I'll mention that you don't have to include "Else" in the "If" statement. For example: Dim Password As String Password = InputBox("Please enter the password") If (Password = "let me in") Then MsgBox "The Password is correct!" End If If the password is correct, The code above will display a message box with the text "The Password is correct!". Otherwise, the code will do nothing, because there is no "Else". Lets see an example of using the operator "Not". Copy the following code to your Form_Load event: Dim Password As String Password = InputBox("Please enter the password") If Not (Password = "let me in") Then MsgBox "Incorrect Password!" End End If The boolean expression: Not (Password = "let me in")
is True only if the Password is not "let me in". Why? If the Password is not "let me in", (Password = "let me in") is False (Figure 3) , and we get the boolean expression: Not (False). Not False = True, so eventually, the expression value is True (Figure 3). Figure 3 Not Not True (Password = "let me in") False
In conclusion, The code above will display a message box with the text "Incorrect Password!" ONLY if the password is different from "let me in" More Advanced Boolean Expressions You can combine the operators "Not", "And" and "Or" in the same boolean expression, using the parentheses "(" and ")" For example: (True And False) Or (Not False) = True Figure 5 (True And False) False
Or
(Not False)
Or True
True
The priority of the "Not" operator is higher than the priority of "And" and "Or" operators. For example: Not True And False = False, because The first operater to be executed is the "Not" (Figure 6): Not True = False.
Then we get the following boolean expression: False And False = False. Figure 6 Not True False And And False If we will executed the "And" operator before the "Not" operator, we would get WRONG answer (Figure 7). Figure 7 Not Not True True And False False False False
A Teaser: What will be printed on the form after executing the following code? Dim Elvis As Boolean Elvis = (Not False And True) And Not ((True And Not False) Or False) Print Elvis
Answer:
Nested Conditional Statements Untill now, we could program simple conditional statements: If the password is xxx - do something, and if not - do other thing. But what if we want to write more complicated conditional statements: If the password is xxx - do something, If the password is yyy - do something else, If the password is zzz - do something else, and if the password is none of the above - do something else. To do that we'll use "ElseIf": Dim Number As Integer Number = InputBox("Please enter your age") If (Number > 50) Then MsgBox "you are older than 50" ElseIf (Number < 20) Then MsgBox "you are younger than 20" Else MsgBox "your age is between 20 and 50" End If How does that code above work: First, the first boolean expression is being evaluated: (Number > 50) If it's equal to True then the line that following it (MsgBox "you are older than 50") will be executed, and the "If statement" will be ended here, so the next boolean expression (Number < 20) will not be checked. If it's equal to False, the next boolean expression will be checked: (Number < 20) If it's equal to True, the line that following it
(MsgBox "you are younger than 20") will be executed, and the "If statement" will be ended here. If it's equal To False, the "Else Statement" will be executed: MsgBox "your age is between 20 and 50" Only 1 of the lines will be executed! You can use more than one "ElseIf" in your "If Statement", For example: Dim Name As String Name = InputBox("Please enter your name") If (Name = "elvis") Then MsgBox "your name is elvis" ElseIf (Name = "tim") Then MsgBox "your name is tim" ElseIf (Name = "john") Then MsgBox "your name is john" ElseIf (Name = "steve") Then MsgBox "your name is steve" Else MsgBox "I don't know you" End If Using "Select Case" The "Select Case" conditional statement is very useful when you have in your conditional statement many conditions. For example, in the last page we had the following code: Dim Name As String Name = InputBox("Please enter your name") If (Name = "elvis") Then MsgBox "your name is elvis" ElseIf (Name = "tim") Then MsgBox "your name is tim" ElseIf (Name = "john") Then MsgBox "your name is john" ElseIf (Name = "steve") Then MsgBox "your name is steve" Else MsgBox "I don't know you" End If When you have many conditions, the "If Statement" become too bulky. In this case, you can use instead of it the "Select Case Statement". The following "Select Case Statement" is do EXACTLY the same thing as the code above: Dim Name As String Name = InputBox("Please enter your name") Select Case Name
Case "elvis": MsgBox "your name is elvis" Case "tim": MsgBox "your name is tim" Case "john": MsgBox "your name is john" Case "steve": MsgBox "your name is steve" Case Else: MsgBox "I don't know you" End Select The "Select Case" syntax is very simple: It Begins with: Select Case VariableName Then comes the conditions. Every condition has "Case" before it, and ":" after it. The "Select Case" conditions are little different from the "If" conditions: The Select Case Condition Case "elvis" Case Is <> "elvis" Case 5 Case Is <> 5 Case Is > 5 Case Is >= 5 Case Is < 5 Case Is <= 5 The equivalent "If" Condition VariableName = "elvis" VariableName <> "elvis" VariableName = 5 VariableName <> 5 VariableName > 5 VariableName >= 5 VariableName < 5 VariableName <= 5
After every condition, comes the line that will be executed if the condition will be "True". For example, the line: Case "elvis": MsgBox "your name is elvis" Is the same as: If (VariableName = "elvis") Then MsgBox "your name is elvis" End If After all conditions, comes the Else condition (It's optional condition, and you can omit it if you want): Case Else:
This condition will be executed ONLY if none of the conditions above was executed. After all of the conditions, the statement closed with End Select
Note that you can have more than 1 line to executed in each condition. For example: Dim Name As String Name = InputBox("Please enter your name") Select Case Name Case "elvis": MsgBox "your name is elvis" MsgBox "you are the king!" MsgBox "I didn't know you are alive!" Case "tim": MsgBox "your name is tim" Case "john": MsgBox "your name is john" Case Else: MsgBox "I don't know you" End Select
Image 2:
(Image 3).
(Image 5).
Image 5:
Change the 'Project Name' to myFirstOCX. This is what you will see, after you complete the control, In the Project->Components menu - where the user choose which OCX controls to add to his project (Image 6).
Image 6:
Right click on the form, and choose properties from the menu. Image 7:
This will be default name of the control when the user will insert it to his form: MyControl1, MyControl2, and so on. Starting the programming Add 1 Command Button to your form (named Command1). Image 9:
This is how your control will look like. Your control is the form and everything on it. We don't want that the control will be a form with a button on it, we want that the control will be a button only, without the form around him. So resize the form to be at the size of the button exactly, so you won't see the form. Image 10:
So now the Control look like a button. But it's not a button, it's a form with button on it. But what if the user will resize the control at design time (like you do to Command Button, after you enter it to your form)? Suppose you have a regular form with a button on it, and the form is resized to the button size (like in your current control). When the user will resize the form, he will see the form that was before 'under' the button. The same thing will happen in our case. To solve this problem, when the user resize the form (i.e the control), we need to resize the button to fit the form and the form will be again at the size of the button. When the user resize the control, he actually try to resize the button. Enter the following code to let the user resize the button instead of resizing the form: Private Sub UserControl_Resize() Command1.Width = UserControl.Width Command1.Height = UserControl.Height End Sub UserControl is the name of the Form/Control. thus, UserControl.Width is the Form/Control width, UserControl.Height is the Form/Control Height and UserControl_Resize() is the event that occur when the user resize the control.
Implementing Control's Properties Every control has few properties as default: Name, Left, Index, Tag, and more. Our control will inherit those properties as default. But we want that our control will have some properties that he doesn't get as default, like Text - the text of the message box that will pop when the user press the button. Implementing Text Property We have 2 occasions: when reading the Text property and when changing the Text property. The reading occasion occur when we want to read the porperty that the user set. For example if the user set the control Text property to "hello", the reading result will return "hello". Lets implement first the reading occasion. Enter the following code to your form: Dim TextVariable As String The TextVariable will be the variable that holds for us the value of the Text property, therefore the String that will be inserted into the message box. Enter the following code to your form: Private Sub UserControl_ReadProperties(PropBag As PropertyBag) TextVariable = PropBag.ReadProperty("Text", "There is no message") End Sub The function above says: read the control's "Text" property. If the reading yield nothing, set as default the Text property to be "There is no message". We called to read the Text property, now we have to implement the reading method: Public Property Get Text() As String Text = TextVariable End Property The TextVariable will hold the Text property value, so we simply need to return the value of TextVariable. TextVariable is a string, and the calling for reading the Text property value will return string, therefore the 'As String' above. Implementing The Writing Method The write occasion occur when the user change the Text property. In that case, we need to update the variable that holds for us the propery value (TextVariable). Enter the Following code to your form:
Private Sub UserControl_WriteProperties(PropBag As PropertyBag) Call PropBag.WriteProperty("Text", TextVariable, "There is no message") End Sub
The function above says: Write the new property value to TextVariable, and update the Text Property. If the writing to the TextVariable return nothing, Set the Text property value to be "There is no message". Now we have to implement the writing method, where the new property value will be entered into the TextVariable. Enter the following code to your form: Public Property Let Text(ByVal New_Text As String) TextVariable = New_Text PropertyChanged "Text" End Property The new Text property value is passed with the New_Text parameter. Of course this parameter have to be String, because the Text property holds String. We set the TextVariable variable to hold the new Text property value. Then we announce that the "Text" property has been changed. Implementing events We know what the user wants to pop up when he clicks the button - the Text in TextVariable. Now we need to pop up the message box when the user click the button. We want 2 events: KeyPress and Click. First we need to declare them. enter the following code to your form: Event Click() Event KeyPress(KeyAscii As Integer) How do we know that the Click event not getting parameters, and the KeyPress event get the KeyAscii parameter? Double Click on the command button. 2 new lines have been inserted to your code: Private Sub Command1_Click() End Sub as you see, the Click event gets no parameters. Now go to the button KeyPress event, via the right ComboBox under the title bar, which now showing the current event - Click After you choose KeyPress from the combobox, 2 new lines were inserted to your code:
As you can see, the button KeyPress event get the KeyAscii parameter.
Implementing The KeyPress Event We don't want to change the KeyPress Event. We want that the code the user will insert to the KeyPress Event (Image 11) will be launched as usual, without any changes. Image 11:
So we will enter the following lines to our form: Private Sub Command1_KeyPress(KeyAscii As Integer) RaiseEvent KeyPress(KeyAscii) End Sub Code Explanation: when the user press on the Command1 Button, simply launch the Control (MyControl) KeyPress event. The 'RaiseEvent' function launch an event. It launch the event with the KeyAscii parameter that has been received from the Command1 KeyPress event. Implementing The Click Event We want to pop up the message box when the Click event occur, and then run the code that the user entered in the MyControl1 - Click event. Enter the following code to your form: Private Sub Command1_Click() MsgBox (TextVariable)
RaiseEvent Click End Sub When the user Click on Command1, pop up a message box with the TextVariable string. Then run the code that the user inserted to the control Click event. What will happen if you omit the 'RaiseEvent Click' line? When the user will click the button, the message box will pop up, and the code that the user entered to the MyControl1 Click event will not be apply. So actually the user will not be able to program the click event.
By now, your code should look like this: Dim TextVariable As String Event Click() Event KeyPress(KeyAscii As Integer) Private Sub Command1_Click() MsgBox (TextVariable) RaiseEvent Click End Sub Private Sub Command1_KeyPress(KeyAscii As Integer) RaiseEvent KeyPress(KeyAscii) End Sub Private Sub UserControl_Resize() Command1.Width = UserControl.Width Command1.Height = UserControl.Height End Sub Public Property Get Text() As String Text = TextVariable End Property Public Property Let Text(ByVal New_Text As String) TextVariable = New_Text PropertyChanged "Text" End Property
Private Sub UserControl_ReadProperties(PropBag As PropertyBag) TextVariable = PropBag.ReadProperty("Text", "There is no message") End Sub Private Sub UserControl_WriteProperties(PropBag As PropertyBag) Call PropBag.WriteProperty("Text", TextVariable, "There is no message) End Sub
Compiling and running the control Now lets see how the control is working by now. Save the project (File->Save Project). Image 12:
lets compile the project to OCX Control. From the menu, choose File->Make MyFirstOCX.ocx Image 13:
Now your OCX Control has been created, AND registered with your system.
Start a new project and enter your control to the project (From the menu choose Project->Components (Image 14) , mark the MyFirstOCX checkBox (Image 15) and press OK) Image 14:
Image 15:
Now you see the new control at the ToolBox. Image 16:
Insert it to your form, resize it to your preferred size, and insert "hello" to the control Text property. Run the program and click the button. A "hello" message box is popping. That's it for now. for more advanced techniques, go to Lesson 2
Lesson 2
Adding more properties to the control Now we want that the control will have all the Command Button properties. lets add the BackColor property. Enter the following code to your form: Public Property Get BackColor() As OLE_COLOR BackColor = Command1.BackColor End Property Public Property Let BackColor(ByVal New_BackColor As OLE_COLOR) Command1.BackColor() = New_BackColor PropertyChanged "BackColor" End Property Enter the following line to the UserControl_ReadProperties function: Command1.BackColor = PropBag.ReadProperty("BackColor", &H8000000F) Enter the following line to the UserControl_WriteProperties function: Call PropBag.WriteProperty("BackColor", Command1.BackColor, &H8000000F) The OLE_COLOR is the type of the BackColor property variable, the same as the Boolean is the type of the Enabled property variable, and the Integer is the type of the Height property variable. What we did now is almost the same as we did with the Text property. The difference is that in the text property we used a variable (TextVariable) to store the property information. Here we not using a variable, we read and write the information directly to the Command1.BackColor property. The Command1.BackColor property is here our variable that store the information. Why is that? Because when the user set the Control BackColor property, we actually want to set the Command1 BackColor property. Suppose the user set the Control BackColor to Black. In that case, We want to set the Command1 BackColor to Black. So actually, the Control BackColor property is the Command1 BackColor property. So instead of reading and writing to variable, we read and write directly to the Command1 BackColor property. It's exactly the same thing with all of the other properties. Adding the rest of the properties Public Property Get Enabled() As Boolean Enabled = Command1.Enabled End Property Public Property Let Enabled(ByVal New_Enabled As Boolean) Command1.Enabled() = New_Enabled PropertyChanged "Enabled" End Property
Public Property Get Font() As Font Set Font = Command1.Font End Property Public Property Set Font(ByVal New_Font As Font) Set Command1.Font = New_Font PropertyChanged "Font" End Property Public Property Get Picture() As Picture Set Picture = Command1.Picture End Property Public Property Set Picture(ByVal New_Picture As Picture) Set Command1.Picture = New_Picture PropertyChanged "Picture" End Property Public Property Get DisabledPicture() As Picture Set DisabledPicture = Command1.DisabledPicture End Property Public Property Set DisabledPicture(ByVal New_DisabledPicture As Picture) Set Command1.DisabledPicture = New_DisabledPicture PropertyChanged "DisabledPicture" End Property Public Property Get MousePointer() As MousePointerConstants MousePointer = Command1.MousePointer End Property Public Property Let MousePointer(ByVal New_MousePointer As MousePointerConstants) Command1.MousePointer() = New_MousePointer PropertyChanged "MousePointer" End Property Public Property Get MouseIcon() As Picture Set MouseIcon = Command1.MouseIcon End Property Public Property Set MouseIcon(ByVal New_MouseIcon As Picture) Set Command1.MouseIcon() = New_MouseIcon PropertyChanged "MouseIcon" End Property Public Property Get Caption() As String Caption = Command1.Caption End Property Public Property Let Caption(ByVal New_Caption As String) Command1.Caption() = New_Caption PropertyChanged "Caption" End Property
Private Sub UserControl_ReadProperties(PropBag As PropertyBag) Command1.BackColor = PropBag.ReadProperty("BackColor", &H8000000F) Command1.Enabled = PropBag.ReadProperty("Enabled", True) Set Font = PropBag.ReadProperty("Font", Ambient.Font) Set Picture = PropBag.ReadProperty("Picture", "") Set DisabledPicture = PropBag.ReadProperty("DisabledPicture", "") Command1.MousePointer = PropBag.ReadProperty("MousePointer", 0) Set MouseIcon = PropBag.ReadProperty("MouseIcon", "") Command1.Caption = PropBag.ReadProperty("Caption", "Button") End Sub Private Sub UserControl_WriteProperties(PropBag As PropertyBag) Call PropBag.WriteProperty("BackColor", Command1.BackColor, &H8000000F) Call PropBag.WriteProperty("Enabled", Command1.Enabled, True) Call PropBag.WriteProperty("Font", Font, Ambient.Font) Call PropBag.WriteProperty("Picture", Picture, "") Call PropBag.WriteProperty("DisabledPicture", DisabledPicture, "") Call PropBag.WriteProperty("MousePointer", Command1.MousePointer, 0) Call PropBag.WriteProperty("MouseIcon", Command1.MouseIcon, "") Call PropBag.WriteProperty("Caption", Command1.Caption, "Button") End Sub The difference between SET and GET As you see, in some of the properties, we use SET instead of GET. When you want to change the Command Button Picture property, you press on the Button with the 3 dots on him that found in the "Picture" cell (Image 17) , and then browse for your picture. Image 17:
When we want to set property that uses the browse button, we use SET instead of GET.
Adding more events Event Event Event Event Event KeyDown(KeyCode As Integer, Shift As Integer) KeyUp(KeyCode As Integer, Shift As Integer) MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer) RaiseEvent KeyDown(KeyCode, Shift) End Sub Private Sub Command1_KeyUp(KeyCode As Integer, Shift As Integer) RaiseEvent KeyUp(KeyCode, Shift) End Sub Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) RaiseEvent MouseDown(Button, Shift, X, Y) End Sub Private Sub Command1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) RaiseEvent MouseMove(Button, Shift, X, Y) End Sub Private Sub Command1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) RaiseEvent MouseUp(Button, Shift, X, Y) End Sub Control's special events Private Sub UserControl_Initialize() End Sub The code that you will insert to this sub, will run when the user first place the control on the form on design time, and on runtime, when the form with the control on it is loaded. Private Sub UserControl_Show() End Sub This event occur instantly after the Initialize event occur. The initialize event occur After the control is loaded and before the Control is visible (to the programmer or the user that run the program) and the Show event occur right after the Control is visible to the programmer/user. You can browse for other event: At the control's code window, choose UserControl from the left ComboBox under the title bar, and choose event with the right ComboBox. Image 18:
Setting Control's properties As you probably saw, when you inserted the control to your project, the control had a default icon on the ToolBox (Image 16) . To set your own Icon, Add your icon to the control ToolBoxBitmap property. Image 19:
Make an About box Make an About property, that when the user will press on the About property cell on the control Properties window, A message box will show up with your details. Add the following code to your form: Public Sub AboutBox() MsgBox "This is my message", , "This is my title" End Sub Now from the menu choose Tools->Procedure Attributes. Image 20:
From the 'Name' combo box choose AboutBox, Click on the Advanced button, and from the 'Procedure ID' choose AboutBox, and press OK. Now a New property has just been added to your control - the About Property. The End.
Some of the controls are invisible at runtime (Like Timer and ImageList). To set your control to be invisible at runtime, Set the control InvisibleAtRuntime property to True.
Then select the VB6 Resource Editor, mark the Loaded/Unloaded check Box, and press OK Image 2:
(Image 2).
You've just added the Resource Editor Add-In. To launch it, click on its icon in the menu (Image 3). Image 3:
Adding image Files to the Resource File To add BMP file to the resource file, click on the "Add Bitmap" icon in the resource editor menu
5).
(Image
Image 5:
Then select your BMP file and press Open. By default it will be saved under 101 ID (Image 6). Image 6:
To add cursor file to the resource file, click on the "Add Cursor" icon in the resource editor menu (Image 7). To add icon, click on "Add Icon" in the resource file menu (Image 8), And to add GIF or JPG file click on "Add Custom Resource" in the menu (Image 9). Image 7:
Image 8:
Image 9:
You can use the "Add Custom Resource" to add Sound Files, Text files, and any other files. Adding image Files to the Resource File (Continue) You can add as much files as you want. Every file has its own ID, so you will be able to access it by its unique ID. Bitmap and Icon, for example, are different resources, so they can have the same ID. But two Bitmaps or two Icons can't have the same ID. If you will add Bitmap, it will be saved in the resource file under the Bitmap "Folder" (It's not really folder, because it's one single file), If you will add Icon, it will be saved under Icon "Folder", and so on
(Image 10).
Image 10:
Renaming the image ID You can rename the image ID by clicking on the image you want to rename (in image 10, for example, I've clicked on 101 in the CUSTOM "Folder") and then clicking on the properties Icon in the menu
(Image 11).
Image 11:
Then, in the Id Text Box, enter the new image ID. The ID Doesn't have to be Number! It can be word, like "Cube" in the example below: Image 12:
After you enter the new ID name for this image, press the OK Button.
In the example that appear in Image 10, I added 1 GIF file ("CUSTOM" Folder), 3 Bitmaps, 1 Cursor and 2 Icons.
Adding the Resource File to your Project After you've added several Image files to the resource file, save it by pressing the save icon in the menu (Image 13).
Image 13:
Choose your resource file name, and press Save. Now not only the resource file was saved, but it been added to your Project. To see it, From Visual Basic menu choose View->Project Explorer (Image 14), and by default, under the Related Documents folder (Image 15), you will see the file Project1.RES (or if you saved the resource file in other name, yourResourceFileName.RES). Image 14:
Image 15:
Adding the Resource File to your Project (Continue) Now you have this resource file in your project. But what if you'll want in the future to add this exactly resource file to your project? would you have to make it again? The answer is no. To add this resource file to a new project, choose from VB Menu Project->Add New Resource File (Image 16) , select this file and press Open. Image 16:
Note that "Add New Resource File" menu item will appear only if you've added the Resource Editor Add-In (I've explained how to add the Resource Editor Add-In in page 2). Accessing BMP, ICO and CUR files from your Program Now you have the resource file with all your image files in it. But how can you access them from your program? Start a new Project, add 1 Picture Box (named Picture1) to your form, and add the following code to the form: Private Sub Form_Load() Picture1.Picture = LoadResPicture(101, vbResBitmap) End Sub This code will load the Bitmap that found under the Bitmap "Folder" in the resource file, with the ID 101, to the Picture Box. Explanation of this code: LoadResPicture function load a picture from the resource file. 101 - the ID of the picture you want to load. if there is no Bitmap in your resource file with the ID 101, an error will occur.
If your picture ID is a word like "Cube" instead of number like 101, you should write: Picture1.Picture = LoadResPicture("Cube", vbResBitmap) Note that the "Cube" is in quotes, and when the ID was a number it was not in quotes. vbResBitmap - Because the picture you want to load is a Bitmap, and it's under the Bitmap "Folder" in the resource file. If you want to load an icon with the ID "myIcon", use LoadResPicture("myIcon", vbResIcon) and if you want to load an cursor with the ID "myCursor" use LoadResPicture("myCursor", vbResCursor) Summary: To load BMP, Ico or Cur file from resource file use: LoadResPicture ("MyImageID", vbRes...) Where vbRes...=vbResBitmap if it's Bitmap file, vbRes...=vbResIcon if it's Icon file, and vbRes...=vbResCursor if it's cursor file. Examples in the next page... Accessing BMP, ICO and CUR files from your Program - Examples The next example will show you how to add an icon to Command Button from resource file. Add an Icon to your Resource File (under the Icon "Folder") and rename its ID to "myIcon". Add 1 Command Button to your form (named Command1). Set the Command Button Style property to 1 - Graphical, so it will be able to display images. Add the following code to your form: Private Sub Form_Load() Command1.Picture = LoadResPicture("myIcon", vbResIcon) End Sub Run the program, and you will see that the icon is displayed on the Command Button. You can load multiple Icons on multiple Command Buttons, and load multiple Bitmaps into multiple Picture Boxes at the same time, as demonstrated below: Image 17:
Accessing BMP, ICO and CUR files from your Program - Examples (Continue) The next example will show you how to change your mouse cursor to other cursor that found in resource file. Add a Cursor to your Resource File (under the Cursor "Folder") and rename its ID to "myCursor". Set the form MousePointer property to 99 - Custom. Add the following code to your form: Private Sub Form_Load() Form1.MouseIcon = LoadResPicture("myCursor", vbResCursor) End Sub Run the program, and you will see that the mouse cursor is the cursor that found in your Resource File, under the "myCursor" ID. That's the end of Lesson 1. For more advanced techniques using Resource File (Like loading GIF, JPG and Sound files from Resource file) go to Lesson 2.
Lesson 2
Accessing GIF and JPG files from your Program There is no Built-In option to load GIF and JPG files, There is no vbResGIF or vbResJPG. So to load these files you'll have to use the following Function: Public Sub LoadDataIntoFile(DataName As Integer, FileName As String) Dim myArray() As Byte Dim myFile As Long If Dir(FileName) = "" Then myArray = LoadResData(DataName, "CUSTOM") myFile = FreeFile Open FileName For Binary Access Write As #myFile Put #myFile, , myArray Close #myFile End If End Sub What does this function do? The function gets two parameters: DataName and FileName. It simply copy the File that found in the resource file, under the CUSTOM "Folder" With the Id that found in DataName variable. The new file name will be the String that found in the FileName variable. For example, assume I have a resource file, with EXE file that found under the CUSTOM "Folder". The EXE file ID is 101. Calling to: LoadDataIntoFile 101, "c:\MyDir\myFile.ddd" Will copy the EXE file to c:\MyDir\myFile.ddd It doesn't matter if the file is EXE, GIF, JPG, TXT or WAV. Because of that, this function can extract any file from resource file, and can be used to extract Sound files, Text files, and other files.
How the LoadDataIntoFile Function works? Public Sub LoadDataIntoFile(DataName As Integer, FileName As String) Declaring myArray and myFile variables Dim myArray() As Byte Dim myFile As Long If Dir("D:\Myfile.Exe") = "" Return True if the file exist and False if doesn't. If the file exist we don't start the copying process, to avoid overwriting an existing file.
If Dir(FileName) = "" Then LoadResData loads file from Resource file that founds under the CUSTOM "Folder", like LoadResPicture loads Picture from resource file that found under all other Folders (Icon, Cursor and Bitmap) In the line below, we load the File that found under the CUSTOM "Folder" with the ID that the DataName variable holds, to the variable myArray myArray = LoadResData(DataName, "CUSTOM") FreeFile is a function that returns the next Free File Number If we wouldn't use FreeFile, and instead we were using: Open FileName For Binary Access Write As #1 And In our code there was before similar line like: Open "Autoexec.Bat" For Binary Access Write As #1 There was a collision because they were both opened As #1 The FreeFile function prevents that and in the example above would open The second file as #2 myFile = FreeFile Opens new file with the name that founds in the FileName variable. Open FileName For Binary Access Write As #myFile Put the myArray variable data into the new file. Remember that the myArray variable holds right now the data of the file we want to copy Put #myFile, , myArray Close the file Close #myFile End If End Sub
Accessing GIF and JPG files from your Program - Example This example will show you how to use the LoadDataIntoFile function to load GIF or JPG file from resource file into Picture Box. Add 1 Picture Box to your form (named Picture1) and add 1 GIF or JPG file to your Resouce File. Set the file ID to be 101. Copy the following code to your form: Public Sub LoadDataIntoFile(DataName As Integer, FileName As String) Dim myArray() As Byte Dim myFile As Long If Dir(FileName) = "" Then myArray = LoadResData(DataName, "CUSTOM") myFile = FreeFile
Open FileName For Binary Access Write As #myFile Put #myFile, , myArray Close #myFile End If End Sub Private Sub Form_Load() 'this will copy the GIF/JPG file to c:\tmpfile.$$$ LoadDataIntoFile 101, "c:\tmpfile.$$$" 'this will load the c:\tmpfile.$$$ file to Picture1 Picture Box Picture1.Picture = LoadPicture("c:\tmpfile.$$$") End Sub
Run the program. The Gif/JPG file will be displayed in the picture Box.
Play Wav file that found in Resource File This example will show you how to play wav file that found in Resource File, using the LoadDataIntoFile function. Add 1 Wav File to your resource file, and set the Wav file ID to be 101. Add the following code to your form: 'the API declaration that play Wav file Private Declare Function sndPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" _ (ByVal lpszSoundName As String, ByVal uFlags As Long) As Long 'the LoadDataIntoFile function Public Sub LoadDataIntoFile(DataName As Integer, FileName As String) Dim myArray() As Byte Dim myFile As Long If Dir(FileName) = "" Then myArray = LoadResData(DataName, "CUSTOM") myFile = FreeFile Open FileName For Binary Access Write As #myFile Put #myFile, , myArray Close #myFile End If End Sub Private Sub Form_Load() 'copy the Wav file to c:\tmpfile.$$$ LoadDataIntoFile 101, "c:\tmpfile.$$$" 'Play the Wav file using the sndPlaySound API function sndPlaySound "c:\tmpfile.$$$", 1 End Sub
Summary
Resource File is very useful when you have a lot of image files in your application, or if you want to decrease the size of your application file. The resource file is intended to deal with BMP, ICO, and Cur files, and you can easily load them from the resource file with Visual Basic Built-In functions. But with additional function that copy the file from the resource file to the hard disk, you can use it with all the types of files.