visual basic material

Upload: karthik-keyan

Post on 02-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 Visual Basic Material

    1/94

    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, ButIf you want to make a really advanced professional game like Quake 2,You may choose other language (like C++), that would be much moreharder to program with.However, Visual Basic will be probably powerful enough to suit all your applicationand 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 easilythan other programming languages.

    3) You can find many tools (Sharewares and Freewares) on the internet that willSpare 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 controlthat does it, and use it in your program.

    Compare to other languages, Visual Basic have the widest variety of toolsthat 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 reallysophisticated games.

    2) It's much more slower than other langauges.

  • 7/27/2019 Visual Basic Material

    2/94

    Getting StartedNote 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 maybe 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))

  • 7/27/2019 Visual Basic Material

    3/94

    Figure 2

    After you've clicked the Open button, you will see:

    Figure 3

  • 7/27/2019 Visual Basic Material

    4/94

    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

    Now your program is running (Figure 5):

  • 7/27/2019 Visual Basic Material

    5/94

    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 buttonin 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 theform's X button instead of the Visual Basic Stop button.It's like shutting Windows From the Start button, instead of Pressingthe Power button.

    Figure 6

  • 7/27/2019 Visual Basic Material

    6/94

    Figure 7

    Learning about Properties

    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

    The properties window looks like this:

  • 7/27/2019 Visual Basic Material

    7/94

    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 theForm'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 theform's properties names column (Figure 10).

  • 7/27/2019 Visual Basic Material

    8/94

    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).

  • 7/27/2019 Visual Basic Material

    9/94

    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 FormThere 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

  • 7/27/2019 Visual Basic Material

    10/94

    And you will see the Toolbox (Figure 14):

    Figure 14

  • 7/27/2019 Visual Basic Material

    11/94

    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

  • 7/27/2019 Visual Basic Material

    12/94

    Now click on the form with the left mouse button, and hold the buttondown while moving the cursor.You will see a rectangle.Release the mouse button, and in the place of the rectangle youwill see a button (Figure 17).

    Figure 17

    Changing the button's PropertiesNow you have a button on your form.You can change its location by dragging it, and change itssize 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 withthe right mouse button and select Properties for the pop-up menu (Figure 18).

    Figure 18

  • 7/27/2019 Visual Basic Material

    13/94

    The Command Button's Properties window (Figure 19):

    Figure 19

    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

  • 7/27/2019 Visual Basic Material

    14/94

    changing the component's Name property.

    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

  • 7/27/2019 Visual Basic Material

    15/94

    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 placedbetween 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 MsgBox "Hello" to the Form_Load event (Figure 21).

    Figure 21

    Now run your program using the Play button.When the program is started, a message box with thetext "Hello" is appear (Figure 22).

    Figure 22

  • 7/27/2019 Visual Basic Material

    16/94

    More EventsThe 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 ofthe 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 ofthe Code Window, where appears right now the text "Load" (Figure 24).

    Figure 24

  • 7/27/2019 Visual Basic Material

    17/94

    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 launchedwhen 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_Unloadevent is being executed and a message box with "GoodBye" text is popping.

    The Command Button's EventsNow 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 clickingthe 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.

  • 7/27/2019 Visual Basic Material

    18/94

    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 beingexecuted, 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

  • 7/27/2019 Visual Basic Material

    19/94

    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 thefollowing line to it:

    Print "This is Command1"

    Select "Command2" (This is the name of the secondCommand 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:

  • 7/27/2019 Visual Basic Material

    20/94

    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.

    http://cuinl.tripod.com/tutorials/f-21.htmhttp://cuinl.tripod.com/tutorials/f-21.htm
  • 7/27/2019 Visual Basic Material

    21/94

    Lesson 2

    Learning about Variables

    Using Variables is one of the most basic and important subjectsin 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 drawerand 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 orthe 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 thenumber -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 %$#@!??? 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 = DeclareMyTest = the name of the new variableAs Integer = The new variable type will be Integer.

    Now you can put a number inside this variable.You can do that by simple write:

  • 7/27/2019 Visual Basic Material

    22/94

    MyTest = 10

    The line above will insert the number 10 into the MyTest variable.Now the MyTest variable stores the Number 10, but howcan 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 foundin the variable.The Print MyTest Line will print the value that found inthe MyTest variable, therefore it will print 10 on the form.

    Working With Integers (Continue)Question: What will be printed on the formafter executing the following code:

    Dim Blah As IntegerPrint BlahBlah = 10Blah = 20Print BlahBlah = 30Print "Blah"Print Blah

    After you've thinking about the answer, you cancheck 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...

    Working With Integers (Continue)Answer:

    020

  • 7/27/2019 Visual Basic Material

    23/94

    Blah30

    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 wedidn'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 nowin the Blah variable - 0

    Blah = 10

    Now the Blah variable holds the number 10

    Blah = 20

    Now the Blah variable holds the number 20What's happened to the 10 that was inside it?It has been deleted!A variable can holds only one value, and whenyou put in it a value, the old value is being immediately deleted.

    So what is the differents between

    Blah = 20

    and

    Blah = 10Blah = 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 nowin the Blah variable - 20

    Blah = 30

  • 7/27/2019 Visual Basic Material

    24/94

    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 formafter executing the following code:

    Dim Blah As IntegerBlah = 2

    Print 2 + 3Print "2 + 3"Print Blah + 3

    Print Blah

    Blah = Blah + 1Print BlahBlah = Blah + Blah

    Print Blah

    The Answer can be found in the next page...

    Working With Integers (Continue)Answer:

    52 + 35236

    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 = 2Now 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.

  • 7/27/2019 Visual Basic Material

    25/94

    The expression will be evaluated: 2 + 3 = 5.The evaluation result is 5, and then Visual Basic willexecute the command Print 5

    So in other words, Print 2 + 3is 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 beingtreated 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 beingreplaced 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 commandthe 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 replacementthe new command will be Print 2

    After executing this command, the value 2will be printed on the form.

    Blah = Blah + 1

    The line above simply says:Put in the Blah variable, the value of the expression Blah + 1The 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 willput 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 + BlahThe computer is first evaluate the expression Blah + BlahBlah is being replaced with its value: 3.After the replacement the computer evaluates the expression 3 + 3.The expression value is 6.

  • 7/27/2019 Visual Basic Material

    26/94

    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 ExpressionsYou 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 TypesWhat will be printed on the form afterexecuting the following code?

    Dim ABC As IntegerABC = 4.8Print ABC

    Answer:The Integer variable can't store a number with fraction,So the computer will round the 4.8 to 5, and willInsert 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 canstore round numbers like the Integer type, and in addition canstore numbers with fractions.

    The Variable types list:

  • 7/27/2019 Visual Basic Material

    27/94

    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) Numbersbetween -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 numbersbetween 0 to 255, while I can use Integer variable that can storenumbers 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 numbersgreater than 255 or less than 0, declare it as Byte variableand 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 DoubleDim Blah As Single

    Dim Popeye As Byte

    And so on.

    Working With StringsString 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 StringAbc = "Good Morning"

    Question: What will be printed on theform after executing the following code?

    Dim kuku As Stringkuku = "Hello!!!"Print "kuku"Print kuku

  • 7/27/2019 Visual Basic Material

    28/94

    Answer:

    kukuHello!!!

    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" withthe 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 StringDim popo As String

    gogo = "Hello"popo = "world"

    gogo = gogo + " !!! " + popoPrint 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 VariablesInsert two Command Buttons to your form (withthe names Command1 and Command2),and Add the following code to your program:

    Private Sub Command1_Click()Dim gogo As Integergogo = 100

    End Sub

    Private Sub Command2_Click()MsgBox gogo

    End Sub

  • 7/27/2019 Visual Basic Material

    29/94

    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 theSub 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 theCommad1_Click event, it's declared only within the sub, andit's not declared in the Command2_Click event.

    So if you want that a specific variable will be "exist" inyour 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 onlywithin 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

  • 7/27/2019 Visual Basic Material

    30/94

    Put the gogo declaration statement in the "Declarations area".Simply write:

    Dim gogo As Integer

    And delete the old statement that foundin 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 areaof 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 theprogram 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, butwe 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 boxwith the value 100 is popping.

  • 7/27/2019 Visual Basic Material

    31/94

    Choosing A Valid Name For VariableWhen declaring on variable, you choose its name.

    For example:

    Dim Tuti As Integer

    The example above will set the variablename to be "Tuti".

    The names you choose for your variables don't have

    to have any meaning, but still there are some limitationsabout the names you can call your variables.

    The Rules:

    1)The only characters that can appear in the name areletters, 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'tuse 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 BasicCommand or Function (these names are been called "saved names").

    For example you can't use the name Print, because there iscommand 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 anywherein 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 continuingwith the next lessons.

    More advanced variables subjects will appearduring the next lessons.

    Go to Lesson 3 to learn more about Events and properties

    http://cuinl.tripod.com/tutorials/f-31.htmhttp://cuinl.tripod.com/tutorials/f-31.htm
  • 7/27/2019 Visual Basic Material

    32/94

    Lesson 3

    The Command Button's KeyPress, KeyDown and KeyUp EventsThe events that will be mentioned in the following pagesare commonly used, and without learning about themyou 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 CommandButton is called by default Command1.

    Copy the following code to the code window (youcan copy and paste it using Ctrl + C for copyingand 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 whenthe 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 arebeing 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:

    http://cuinl.tripod.com/tutorials/f-12.htmhttp://cuinl.tripod.com/tutorials/f-12.htm
  • 7/27/2019 Visual Basic Material

    33/94

    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, theKeyDown and the KeyPress events are being executed inthis 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 ParametersParameters 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 withempty parentheses () and the KeyPress event's first

    line is ended with (KeyAscii As Integer)

    What is the (KeyAscii As Integer) ?

  • 7/27/2019 Visual Basic Material

    34/94

    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 userpress a key, and This variable holds the Ascii value of thekey that been pressed.With This Ascii value you can know on which keythe 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 AsciiHow 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.

  • 7/27/2019 Visual Basic Material

    35/94

  • 7/27/2019 Visual Basic Material

    36/94

    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.

    MouseMove, MouseDown and MouseUp Events

    Lets check out the Command Button's MouseMove,MouseDown and MouseUp events.

    We will do that like we've done before,by inserting different Print commands to every event.

    Copy the following code to your program:

    Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y AsSingle)

    Print "MouseDown"End Sub

    Private Sub Command1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y AsSingle)

    Print "MouseMove"End Sub

    Private Sub Command1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y AsSingle)

    Print "MouseUp"End Sub

    Run the program.Move the mouse over the form - nothing is happening.

    Move the mouse over the Button - The Button's MouseMove eventis being executed every time you move the mouse over it, therefore

    you see that "MouseMove" is being printed on the formevery time you move your mouse over the button.

    Click on one of the mouse buttons when the mouse is over the button,

    and hold the button down.The MouseDown event is being executed.Release the button, and the MouseUp event is being executed.

  • 7/27/2019 Visual Basic Material

    37/94

    MouseMove, MouseDown and MouseUp Events (Continue)

    Lets check out these events parameters.

    Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y AsSingle)

    Each one of these events gets the same parameters:

    Button, Shift, X and Y.

    The Shift parameter is the same as the KeyDownevent's Shift paramater.

    For example, if you'll press the Shift button while clickingthe mouse, the Shift value will be 1.

    The Button parameter value is 1 if you've clickedthe left mouse button, and 2 if you've clicked the

    right one.

    The X and Y parameters are the X and Y coordinates ofthe 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 itthe Y coordinates (For example, the line:Print "Hello", "World"

    will print: Hello World).

    Additional Command Button's PropertiesAdd 1 Command Button to your form,and change the following properties tosee what they do.

    Caption - the text that appear on the button

    Font - The Caption's font (Figure 2).

  • 7/27/2019 Visual Basic Material

    38/94

    Figure 2

    ToolTipText - Insert into this property the textthat will appear when the mouse is stand stillon the button (Figure 3).

    Figure 3

    Enabled - Setting this property to "False" will makethe button be gray, and the user will no be able to press on it (Figure 4).

    Figure 4

  • 7/27/2019 Visual Basic Material

    39/94

    BackColor - This is the background color of the button (Figure 5).This property will take affect only after you will set theButton'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 willtake affect only after you will set theButton's Style property to 1 - Graphical

    Figure 6

    DisabledPicture - The Picture that will appear on the button whenit disabled (When the Enabled property is "False", like in Figure 4).

    DownPicture - The Picture that will appear on the button whenthe button is being pressed.

    Visible - If you will set this property to "False", the Buttonwill 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.

  • 7/27/2019 Visual Basic Material

    40/94

    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 PropertiesThe 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

  • 7/27/2019 Visual Basic Material

    41/94

    MaxButton - Set this property to "False" to disableThe title bar Maximize Button.

    MinButton - Set this property to "False" to disableThe title bar Minimize Button.

    ShowInTaskbar - Setting this property to "False" willcause the form not showing in the task bar.

    WindowState - The initial appearance style of the form:Minimized, Maximized, or normal.

    The Form's KeyPreview PropertyTo 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" onthe form when the Command Button's KeyPress eventwill 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

  • 7/27/2019 Visual Basic Material

    42/94

    "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 KeyPreviewproperty 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 executedbefore the Button's event.

    Setting Properties At Run-TimeBy now you know how to set a componentproperty 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 ButtonWith the name "Command1", and we want toset 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 yourCommand1 Click event, run the programand 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 StringMyVar = "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.

  • 7/27/2019 Visual Basic Material

    43/94

    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, butVisual 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 = FalseForm1.Enabled = True

    Some of the properties values has the following syntax:

    Number - String

    For example, the Command Button's Style property canget 2 values:

    0 - Standard1 - Graphical

    To set these properties value, omit the string.For example:

    Command1.Style = 1Form1.WindowState = 2

    Some properties represent graphics, for exampleThe Picture property.

    To set these properties at run-time, usethe 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 PropertyYou can set the BackColor property at run-time in 2 ways.

    Way 1: Using the Color's numeric valueEvery 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&

  • 7/27/2019 Visual Basic Material

    44/94

  • 7/27/2019 Visual Basic Material

    45/94

    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 learna little bit about Constants.All of this in the next page...

    Setting the BackColor Property (Continue)

    Way 2: Using the Colors ConstantsFirst 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 valueof 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, becausevbRed = &H000000FF&

    Where are these constants came from?Visual Basic automatic declare them

    when the program starts.

  • 7/27/2019 Visual Basic Material

    46/94

    Imagine it like as the following code isautomatic being entered to your program:

    Dim vbRed As LongvbRed = &H000000FF&

    Dim vbBlue As LongvbBlue = &H00FF0000&

    And so on...

    But with one exception: You can'tchange 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 constvariable 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 likeconditional statements, go to the Conditional Statements Tutorial.

    http://cuinl.tripod.com/tutorials/f-41.htmhttp://cuinl.tripod.com/tutorials/f-41.htm
  • 7/27/2019 Visual Basic Material

    47/94

    Conditional Statements Tutorial

    What Are Conditional Statements?Suppose you want to protect your program with password.You ask from the user to enter the password.If the password is correct - you want to let the user in, if not - you want to end the program.

    To do this, you have to use conditional statement becausethe code you will execute (let the user in or end the program) isdepend on what is the password that the user has entered.

    One of the basics of Conditional statement are Boolean variables.Boolean variables are commonly used in programming,and you have to understand them before continuing with conditional statements.

    Boolean Variables

    As we learnt, String variables store text, andInteger Variables Store numbers.Boolean variable stores one of the following constant values:

    "True", or "False".

    For example:

    Dim Kuku As BooleanKuku = TrueDim YoYo As BooleanYoYo = False

    What are the True and False stand for?They are the result of every "Boolean expression".

    Boolean Expressions

    Boolean expression is like a question thatthe answer to it is "True" or "False"

    For example:Is 4 Plus 6 is 10? TrueIs 2 bigger than 4? False

    But the questionHow much is 4 Plus 6?Is not a boolean expression, because its answeris 10 (and not True or False)

    Examples of Boolean expressions in the next page.

    Examples Of Boolean Expressions

    The following code:

    Dim ABC As BooleanABC = (3 > 4)Print ABC

  • 7/27/2019 Visual Basic Material

    48/94

    Will print "False" on the form.The value of the boolean expression 3 > 4is "False", because 3 is not greater than 4.

    The following code:

    Dim ABC As BooleanABC = ("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 BooleanDim A As IntegerDim B As Integer

    A = 1B = 2ABC = (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

  • 7/27/2019 Visual Basic Material

    49/94

    Example:Put 1 Command button on your form andenter the following code to its click event:

    Dim Elvis As StringElvis = InputBox("Please Enter your name")Print Elvis

    Run the program and click the button.

    A Message Box is appearing with thetext "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 StatementsThe syntax of the conditional statement:

    If (boolean expression) ThenThe code to execute if the boolean expression is equal to True

    ElseThe 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 passwordat the very start of the program, so put the followingcode in the Form_Load event:

    Dim Password As StringPassword = InputBox("Please enter the password")If (Password = "let me in") Then

    MsgBox "The Password is correct!"

  • 7/27/2019 Visual Basic Material

    50/94

    ElseMsgBox "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 thetext "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 codethat will be executed is the code that located betweenthe Then and the Else (MsgBox "The Password is correct!")

    If this boolean expression's value is False, and thishappens when the Password variable value is NOT "let me in",the code that will be executed is the code that located betweenthe 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 StringPassword = 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 morecomplicated boolean expression.

    In the last example we used the booleanexpression Password = "let me in".

    This boolean expression is "True" ifthe Password is "let me in", and "False"

  • 7/27/2019 Visual Basic Material

    51/94

    If the Password is not.

    How can we make a boolean expressionthat will be "True" if the Password is"let me in" or "sam sent me", and if thePassword is other than the two above, theboolean 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 StringPassword = 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 = 11But 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 = TrueTrue Or False = TrueTrue Or True = TrueFalse Or False = False

    The 4 examples above are the only optionsof using the "Or" operator.

    Lets see what effect has the "Or" operator onthe boolean expression we used:

    (Password = "let me in") Or (Password = "sam sent me")

    First, the left and right boolean expressionsare being evaluated (Figure 2).

  • 7/27/2019 Visual Basic Material

    52/94

    For example, if the Password is "let me in" then(Password = "let me in") is Trueand (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 = TrueSo the final result of the expression is True (Figure 2).

    Figure 2

    (Password = "let me in") Or (Password = "sam sent me")

    True Or False

    True

    This boolean expression will be True ifthe 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 = TrueTrue And False = FalseFalse And True = FalseFalse And False = False

    When using the "And" operator, theexpression will be True only if bothboolean expressions are True.

    For example, copy the following codeto your Form_Load event:

    Dim UserName As StringDim 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!"

  • 7/27/2019 Visual Basic Material

    53/94

    EndEnd 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 nameand 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, becauseTrue And True = True, and any othercombination is equal to False.

    Using The "Not" OperatorThe "Not" operator has very simple function:

    Not True = FalseNot 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 StringPassword = 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 abovewill 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 StringPassword = 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")

  • 7/27/2019 Visual Basic Material

    54/94

    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, theexpression value is True (Figure 3).

    Figure 3

    Not (Password = "let me in")

    Not False

    True

    In conclusion,The code above will display a message box

    with the text "Incorrect Password!" ONLY ifthe password is different from "let me in"

    More Advanced Boolean Expressions

    You can combine the operators "Not", "And" and "Or" inthe same boolean expression, using the parentheses "(" and ")"

    For example:

    (True And False) Or (Not False) = True

    Figure 5

    (TrueAnd

    False)Or (Not False)

    False Or True

    True

    The priority of the "Not" operator is higher thanthe priority of "And" and "Or" operators.

    For example:

    Not True And False = False, becauseThe first operater to be executed is the "Not" (Figure 6):Not True = False.

  • 7/27/2019 Visual Basic Material

    55/94

    Then we get the following boolean expression:False And False = False.

    Figure 6

    Not True And False

    False And False

    False

    If we will executed the "And" operator beforethe "Not" operator, we would get WRONG answer (Figure 7).

    Figure 7

    Not True And False

    Not False

    True

    A Teaser:What will be printed on the form after

    executing the following code?

    Dim Elvis As BooleanElvis = (Not False And True) And Not ((True And Not False) Or False)

    Print Elvis

  • 7/27/2019 Visual Basic Material

    56/94

  • 7/27/2019 Visual Basic Material

    57/94

    (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 StringName = 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 statementis very useful when you have in your conditionalstatement 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 samething as the code above:

    Dim Name As StringName = InputBox("Please enter your name")Select Case Name

  • 7/27/2019 Visual Basic Material

    58/94

    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 The equivalent "If" Condition

    Case "elvis" VariableName = "elvis"

    Case Is "elvis" VariableName "elvis"

    Case 5 VariableName = 5

    Case Is 5 VariableName 5

    Case Is > 5 VariableName > 5

    Case Is >= 5 VariableName >= 5

    Case Is < 5 VariableName < 5

    Case Is

  • 7/27/2019 Visual Basic Material

    59/94

    This condition will be executed ONLY if noneof 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 executedin each condition. For example:

    Dim Name As StringName = 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

  • 7/27/2019 Visual Basic Material

    60/94

    Make Your First ActiveX Control

    Lesson 1

    First of all, what is ActiveX Control?

    ActiveX control is control like all visual basiccommon controls: Command Button, Label, etc.You can make your own ActiveX control, for examplehover button control, and use it in every VB programyou make without addition of code.Instead of writing the same code every time you wantto use the hover button, make once hover buttonActiveX control, and drag it to your form every time youwant to use it, like it was the usual Command Button.

    How can you make your own ActiveX control?In this tutorial we will make a button control, that will popa message box when the user will click on it.I know that it's not very useful, and for this purpose youdon't have to make an ActiveX control, but this examplewill teach you how to make an ActiveX control.

    Getting started

    Choose from the menu (in VB 6.0) File->New Project

    Image 1:

  • 7/27/2019 Visual Basic Material

    61/94

    Select ActiveX Control and press OK.

    Image 2:

    A new form without a title bar has been opened (Image 3).

    Image 3:

  • 7/27/2019 Visual Basic Material

    62/94

    Choose from the menu Project->Project1 Properties.

    Image 4:

  • 7/27/2019 Visual Basic Material

    63/94

    In the 'Project Name' Text Box is written by default 'Project1' (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 choosewhich OCX controls to add to his project (Image 6).

  • 7/27/2019 Visual Basic Material

    64/94

    Image 6:

  • 7/27/2019 Visual Basic Material

    65/94

    Right click on the form, and choose properties from the menu.

    Image 7:

    The form's name property by default is UserControl1.Change it to MyControl.

    Image 8:

    This will be default name of the control when the user willinsert it to his form: MyControl1, MyControl2, and so on.

    Starting the programmingAdd 1 Command Button to your form (named Command1).

    Image 9:

  • 7/27/2019 Visual Basic Material

    66/94

    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 buttoninstead of resizing the form:

    Private Sub UserControl_Resize()Command1.Width = UserControl.Width

    Command1.Height = UserControl.HeightEnd 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.

  • 7/27/2019 Visual Basic Material

    67/94

    Implementing Control's PropertiesEvery 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 thathe doesn't get as default, like Text - the text of the message boxthat will pop when the user press the button.

    Implementing Text PropertyWe have 2 occasions: when reading the Text property andwhen changing the Text property.The reading occasion occur when we want toread 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 theString 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 propertyto 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 = TextVariableEnd 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 MethodThe write occasion occur when the user change the Text property.In that case, we need to update the variable thatholds for us the propery value (TextVariable).

    Enter the Following code to your form:

  • 7/27/2019 Visual Basic Material

    68/94

    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_TextPropertyChanged "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 eventsWe know what the user wants to pop up when heclicks 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:

  • 7/27/2019 Visual Basic Material

    69/94

    Private Sub Command1_KeyPress(KeyAscii As Integer)End Sub

    As you can see, the button KeyPress event get the KeyAscii parameter.

    Implementing The KeyPress EventWe don't want to change the KeyPress Event.We want that the code the user will insert to theKeyPress 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 beenreceived from the Command1 KeyPress event.

    Implementing The Click Event

    We want to pop up the message box when theClick event occur, and then run the code thatthe user entered in the MyControl1 - Click event.

    Enter the following code to your form:

    Private Sub Command1_Click()MsgBox (TextVariable)

  • 7/27/2019 Visual Basic Material

    70/94

    RaiseEvent ClickEnd Sub

    When the user Click on Command1, pop up a message boxwith 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 Clickevent 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 ClickEnd Sub

    Private Sub Command1_KeyPress(KeyAscii As Integer) RaiseEvent KeyPress(KeyAscii)End Sub

    Private Sub UserControl_Resize()Command1.Width = UserControl.WidthCommand1.Height = UserControl.Height

    End Sub

    Public Property Get Text() As String Text = TextVariableEnd Property

    Public Property Let Text(ByVal New_Text As String)TextVariable = New_TextPropertyChanged "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

  • 7/27/2019 Visual Basic Material

    71/94

    Compiling and running the controlNow 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 and press OK.

    Image 13:

  • 7/27/2019 Visual Basic Material

    72/94

    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:

  • 7/27/2019 Visual Basic Material

    73/94

    Image 15:

    Now you see the new control at the ToolBox.

    Image 16:

  • 7/27/2019 Visual Basic Material

    74/94

    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

    http://cuinl.tripod.com/tutorials/ocx-21.htmhttp://cuinl.tripod.com/tutorials/ocx-21.htm
  • 7/27/2019 Visual Basic Material

    75/94

    Adding more properties to the controlNow 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_COLORBackColor = Command1.BackColor

    End Property

    Public Property Let BackColor(ByVal New_BackColor As OLE_COLOR)Command1.BackColor() = New_BackColorPropertyChanged "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 useda variable (TextVariable) to store the property information.Here we not using a variable, we read and write the informationdirectly to the Command1.BackColor property.

    The Command1.BackColor property is here our variable that storethe 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 theCommand1 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 BooleanEnabled = Command1.Enabled

    End Property

    Public Property Let Enabled(ByVal New_Enabled As Boolean)Command1.Enabled() = New_EnabledPropertyChanged "Enabled"

    End Property

  • 7/27/2019 Visual Basic Material

    76/94

    Public Property Get Font() As FontSet Font = Command1.Font

    End Property

    Public Property Set Font(ByVal New_Font As Font)Set Command1.Font = New_FontPropertyChanged "Font"

    End Property

    Public Property Get Picture() As PictureSet 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 PictureSet DisabledPicture = Command1.DisabledPicture

    End Property

    Public Property Set DisabledPicture(ByVal New_DisabledPicture As Picture)Set Command1.DisabledPicture = New_DisabledPicturePropertyChanged "DisabledPicture"

    End Property

    Public Property Get MousePointer() As MousePointerConstantsMousePointer = 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 PictureSet MouseIcon = Command1.MouseIcon

    End Property

    Public Property Set MouseIcon(ByVal New_MouseIcon As Picture)Set Command1.MouseIcon() = New_MouseIconPropertyChanged "MouseIcon"

    End Property

    Public Property Get Caption() As StringCaption = Command1.CaptionEnd Property

    Public Property Let Caption(ByVal New_Caption As String)Command1.Caption() = New_CaptionPropertyChanged "Caption"

    End Property

  • 7/27/2019 Visual Basic Material

    77/94

    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 GETAs 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 thatfound 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.

  • 7/27/2019 Visual Basic Material

    78/94

    Adding more events

    Event KeyDown(KeyCode As Integer, Shift As Integer)Event KeyUp(KeyCode As Integer, Shift As Integer)Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)Event 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 whenthe 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 beforethe 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:

  • 7/27/2019 Visual Basic Material

    79/94

    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 boxMake an About property, that when the user willpress 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:

  • 7/27/2019 Visual Basic Material

    80/94

    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.

  • 7/27/2019 Visual Basic Material

    81/94

    Working With Resource File

    Lesson 1

    What is Resource File?Resource file is file that can contains multiple image files (BMP, GIF, JPG, ICO and more), Cursors

    (CUR), Sound files and other files.All these files can be in single Resource file, and you can access them from your program. Forexample, you can load an icon from resource file to your Command Button.Resource file has RES extension.

    Why should I use Resource File?Resource file is very useful when you use the same image several times in your code.For example, you have two Command Buttons with the same icon or two Picture Boxes with the sameBMP picture.If you won't use resource file, but simply add the same icon to both Command Buttons Pictureproperty, the icon will be embedded in each of the Command Buttons. so actually, your icon will besaved twice, and your application file will be bigger.

    If you'll use resource file, you will have only 1 icon saved in your application.

    Launching the Resource EditorFor making resource file, you have Visual Basic Add-In called Resource Editor.To launch it, From VB Menu choose Add-Ins->Add-In Manager (Image 1).

    Image 1:

    Then select the VB6 Resource Editor, mark the Loaded/Unloaded check Box, and press OK (Image 2).

    Image 2:

  • 7/27/2019 Visual Basic Material

    82/94

    You've just added the Resource Editor Add-In.To launch it, click on its icon in the menu (Image 3).

    Image 3:

    And the Resource Editor will appear on your screen:

    Image 4:

  • 7/27/2019 Visual Basic Material

    83/94

    Adding image Files to the Resource FileTo add BMP file to the resource file, click on the "Add Bitmap" icon in the resource editor menu (Image5).

    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 (Image7). To add icon, click on "Add Icon" in the resource file menu (Image 8), And to add GIF or JPG file clickon "Add Custom Resource" in the menu (Image 9).

    Image 7:

  • 7/27/2019 Visual Basic Material

    84/94

    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 reallyfolder, 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:

  • 7/27/2019 Visual Basic Material

    85/94

    Renaming the image IDYou 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 themenu (Image 13).

  • 7/27/2019 Visual Basic Material

    86/94

    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 theRelated Documents folder (Image 15), you will see the file Project1.RES (or if you saved the resource filein other name, yourResourceFileName.RES).

    Image 14:

  • 7/27/2019 Visual Basic Material

    87/94

    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 tomake 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:

  • 7/27/2019 Visual Basic Material

    88/94

    Note that "Add New Resource File" menu item will appear only if you've added the Resource EditorAdd-In (I've explained how to add the Resource Editor Add-In in page 2).

    Accessing BMP, ICO and CUR files from your ProgramNow 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 tothe 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 ID101, 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.

    http://cuinl.tripod.com/tutorials/res-12.htmhttp://cuinl.tripod.com/tutorials/res-12.htm
  • 7/27/2019 Visual Basic Material

    89/94

    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" inthe 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" useLoadResPicture("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, andvbRes...=vbResCursor if it's cursor file.

    Examples in the next page...

    Accessing BMP, ICO and CUR files from your Program - ExamplesThe 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