Results 1 to 1 of 1
  1. #1
    VIP FreckleS's Avatar
    Join Date
    Jan 2007
    Location
    Australia
    Posts
    2,121

    Visual Basic Tutorial

    Hello, throughout this post I will teach you the basics of Visual Basic (.NET). Before we start I would like to clear up some things.
    I am not saying that everything in this tutorial is 100% correct, if it was I would probably be getting paid millions. I also would like to point out that this has no benefit to me, I know the language, you don't so if you find something that is wrong or isn't explained well don't get grumpy and rage at me, ask me to clarify it for you and I will do my best.
    This is only a beginners tutorial, you should not assume total knowledge of Visual Basic after reading this, it will give you enough information to be able to develop "decent" software whilst you continue to broaden your knowledge.

    Who am I?
    I am FreckleS. I have been developing software in Visual Basic for over 4 years and other languages like C/C++ for 3.
    This tutorial may only be posted on my chosen sites which are listed in credits, it may be linked to with credits to me. If you wish to post this on another site, ask me and chances are I will let you.

    There might well be a few details here and there and spelling mistakes etc wrong so please if I have made mistakes please pm me them and don't fill the thread with them, I will fix them asap.

    First off I am not going to show you how to install VB and create a new project and all that crap as you should be able to that before you start this tutorial.

    I will use Console Applications as it saves me a lot of time creating Forms and taking screenshots for you and all that crap.

    Lesson 1 - Good Ol' Hello World
    The code that most programmers start with, Hello World. The Hello World program is one of the most basic programs that can be created in any language. Even though it is extremely simple it still has a few key parts to it.
    Code:
    ' Lesson1 - Hello World
    Module Lesson1
        Sub Main()
            Console.WriteLine("Hello World")
            Console.ReadLine()
        End Sub
    End Module
    On the first line you see:
    Code:
    'Lesson1 - Hello World
    This is a comment, any text that follows a "'" is considered to be a comment. The compiler will ignore this line.

    Comments are one of the most useful types of internal documentation that can be included in a program. Although in this example it would probably be not needed it is good to start good programming practices from your very first application.

    Line 3 is one of the most important parts of the program.
    Code:
        Sub Main()
    Tells the compiler that this is the main function or sub routine. Every Visual Basic Console Application will have this function by default, or you can set the startup function to be something else, I suggest not doing this at least until you are more comfortable with the language as it is not overly needed.

    Line 4 is what makes your program actually "talk"
    Code:
            Console.WriteLine("Hello World")
    This does exactly what you think it does. It writes the text "Hello World" to the Console Window.

    WriteLine and many other functions are member functions of the Class "Console". The Console Class has many properties which can be set through the say way as you just wrote a line to the console, Class.Function or Class.Property = whatever.

    Line 5 is just a line of code that makes a program pause and wait for the user to hit a key before exiting so that we can read the output.
    Code:
            Console.ReadLine()
    Again you see the use of the Console Class. You will soon become more familiar with ReadLine function as it is often used to give variables values etc.

    Line 6 you tell the compiler that it is the end of your sub routine.

    Lesson 2 - Variables
    Just like in math and algebra something that changes its value is called a variable, the same rule applies in programming.

    Variables are a key part of a program for any language and the same applies for Visual Basic. A variables value can be changed with the Assignment Operator (=), you will learn more about this in the coming lessons.

    A variable must have a name and data type before it can be used, this is called declaring. In Visual Basic you can declare variables by the following syntax.
    Code:
    Dim <name> As <type>
    So if I wanted to declare a variable to hold my age I would declare it like this
    Code:
    Dim myAge As Integer
    This tells the compiler to set aside memory to hold an Integer (4 bytes usually) for the variable myAge.

    Now that the variable has been declared we can set its value, get its value and use it for many other purposes.

    Remember the Assignment Operator (=)?
    Visual Basic is a language that has the same operator for testing equality and assigning values.
    Example.
    Code:
    myAge = 15
    Is a good use of the Assignment Operator
    Code:
    If myAge = 15 Then
    Is a good use of the Equality Operator to test a value.

    Not only can you set the value of a variable you can get it and use it.
    Code:
    ' Lesson 2 - Variables
    Module Lesson2
        Sub Main()
            Dim myAge As Integer ' Declare myAge variable as type Integer
            myAge = 15 ' Assign myAge with 15
            Console.WriteLine("I am {0} years old", myAge) ' Write myAge to the screen
            Console.ReadLine() ' Wait for key press
        End Sub
    End Module
    Line 6 is a demonstration on how to write a variables value to the console window. you might think "what the hell is {0}" this tells the compiler that console.writeline will take 2 arguments now, not just the message but it will take an object in an argument. It also says take the value of the object and place it here.

    Another way of writing this would be to join the values.
    Code:
            Console.WriteLine("I am " & myAge & " years old") ' Write myAge to the screen
    This looks messier although neither has a real benefit over the other it is just preference and neater code. All of which comes back to easier manageable code which in turn makes for better code.

    The main datatypes are the following:

    • Integer
    • Single
    • Double
    • Boolean
    • String
    • Byte
    • Char
    • Decimal



    For an understanding of the datatypes read http://www.rentron.com/datatypes.htm

    Quick Note - Understanding Operators
    There are a few types of operators available to Visual Basic, as well as other languages, that make our lives easier. These include, mathematical, relational, logical and assignment operators.

    In Visual Basic unlike a few other languages it has the same Assignment Operator and the same Equality Operator which is a member of the Relational Operator family. They are both (=). I personally am not sure if I like this prefered to a language like C++ where the equality operator is (==).

    Relational Operators:
    Here is a quick list of the relational operators:
    Name, Operator, Sample, Evaluates
    Equals, =, 10 = 20, False
    Not Equals, <>, 10 <> 20, True
    Greater Than, >, 10 > 20, False
    Less Than, <, 10 < 20, True
    Greater Than or Equal to, >=, 10 >= 20, False
    Less Than or Equal to, <=, 10 <= 20, True

    Logical Operators:
    And, Or, Not, AndAlso, Xor, OrElse
    They work in the way in which you might expect.

    And:
    It is used to evaluate two expressions. If both are correct then it will return true if not it will return false.

    Or:
    It is used to evaluate two expressions. If either one is correct then it will return true, if neither are correct it will return false.

    Not:
    It is used to evaluate an expression. If the expression evaluates to false then it will return true. It is has much or less the same effect as <>.

    Mathematical Operators:
    Like you would expect in maths, plus (+), minus (-), multiplication (*), division (/) and modulus (Mod)

    You should be fairly comfortable with the mathematical operators except for perhaps modulus. A good example of the modulus operator would be to find if a number was even or not. Modulus returns the remainder of a division.
    So 10 Mod 2 = 0 because it is evenly divisible.
    Code:
    Module Module1
        Sub Main()
            Console.WriteLine("Enter Number: ")
            Dim num As Integer
            num = Console.ReadLine
            If num Mod 2 = 0 Then
                Console.WriteLine("Even!")
            Else
                Console.WriteLine("Odd!")
            End If
            Console.ReadLine()
        End Sub
    End Module
    You can review more about operators here:
    http://www.startvbdotnet.com/language/operators.aspx

    Lesson 3 - If/Else Statements
    The 3 Control Structures for any program as my software teacher keeps reminding me is Sequence, Selection and Repition.

    If/Else Statements fall into the Selection catagory of these structures. It is just like it sounds, it will select which path to take. Code will always follow Sequence, it is a control structure that will always be, code will always flow, one statement after the other.
    In some cases it will take a different path (selection) or it might go over the same path again (repeition).

    Obviously you can't always know what a user is going to enter into your program so you need to be able to handle this, if you don't you program will most likely crash or something else bad will happen. If/Else Statements are a great way of handling exceptions and keeping your program bug free. The only better way of handling exceptions would be Try/Catch Statement but we will look into that later.

    The Syntax for a If/Else Statement is.
    Code:
    If <Expression> Then
    <Statements>
    Else
    <Statements>
    End If
    We used a very basic If Statement in the last lesson, although the code was unfinished it should have given you an overview of the statement.
    Code:
    ' Lesson 3 - If/Else Statements
    Module Lesson3
        Sub Main()
            Dim myAge As Integer ' Declare myAge variable as type Integer
            myAge = 15 ' Assign myAge with 15
            If myAge = 15 Then ' Is myAge variable equal to 15?
                ' Yes
                Console.WriteLine("I am {0} years old", myAge) ' Write myAge to the screen
            Else
                ' No
                Console.WriteLine("I am not {0} years old", myAge) ' Write error to the screen
            End If ' Close if/else statement
    
            Console.ReadLine() ' Wait for key press
        End Sub
    End Module
    Obviously this will write the message "I am 15 years old" because you have assigned the variable myAge to be 15. This is just a basic example of the statement. Next we will look at user input to help make this and other programs a bit more functional.

    Lesson 4 - User Input
    In most of your applications you are going to need user input to select something, change a setting or whatever. You can achieve this by using the Console Class again as we have been using all the way through this tutorial.

    We can use almost the exact same program from Lesson 3 or even Lesson 2 only with a minor change.
    When we assign the value of myAge we are not going to give it a value, but more we are going to give it a function to run which will return a value and assign it to myAge variable. The definition of the ReadLine function is:

    Code:
    Public Shared Function ReadLine() As String
         Member of System.Console
    Summary:
    Reads the next line of characters from the standard input stream.
    
    Return Values:
    The next line of characters from the input stream, or null if no more lines are available.
    
    Exceptions:
    System.IO.IOException: An I/O error occurred.
    System.OutOfMemoryException: There is insufficient memory to allocate a buffer for the returned string.
    System.ArgumentOutOfRangeException: The number of characters in the next line of characters is greater than System.Int32.MaxValue.
    Basically all that that says is that it calls the member function ReadLine of class Console (System.Console to be 100%) and then returns the next line of character entered.

    Our assignment of myAge should now look like.
    Code:
    myAge = Console.ReadLine()
    That been said you should be able to implement it into your previous programs, I will do it with Lesson 3 so that we can use If/Else statements and also it is good to practice as you will learn from doing.

    You should also print a message before recieving input, something like "Please enter my age: " or something like that. You can do this by the member function WriteLine of class Console (You should remember).

    Code:
    ' Lesson 4 - User Input
    Module Lesson4
        Sub Main()
            Dim myAge As Integer ' Declare myAge variable as type Integer
            Console.WriteLine("Please enter my age: ")
            myAge = Console.ReadLine() ' Assign myAge with user input
            If myAge = 15 Then ' Is myAge variable equal to 15?
                ' Yes
                Console.WriteLine("I am {0} years old", myAge) ' Write myAge to the screen
            Else
                ' No
                Console.WriteLine("I am not {0} years old", myAge) ' Write error to the screen
            End If ' Close if/else statement
    
            Console.ReadLine() ' Wait for key press
        End Sub
    End Module
    Lesson 5 - Functions/Sub Routines
    This and the next lesson, Variable Scope, go hand in hand with each other. Throughout these tutorials I am going to refer to Sub Routines and Functions as the same thing, which they basically are, I do this because of my obession with C++ and other languages (foolish me...)

    The really only difference is that a function returns a value, there are a couple of minor differences but nothing you need to worry about in these tutorials. Oh and of course the other difference. The keywords are different.

    Keywords are words that are set aside by the compiler to be "special". You can't use these words in declarations etc, you can't name an integer variable like.
    Code:
    Dim integer As Integer
    Anyway...

    Functions are the building blocks of programs, commercial software will have a huge number of functions in it. Functions allow you to split your program into parts which makes your program much easier to maintain for other programmers who might come into contact with your code.

    In Visual Basic unlike in other languages like C++ you don't need a function prototype before using your function. You can declare the function by using the following syntax.
    Code:
    Function <Name>(Arguments) As <Type>
    <Statements>
    Return <Value>
    End Function
    You should always take care when naming your functions. A function should only do one task and it should be named according to that task.

    An example is the Doubler function. It takes a number as an argument then it returns the value twice the number passed to it.

    Code:
    ' Lesson 5 - Functions/Sub Routines
    Module Lesson5
        Sub Main()
            Console.WriteLine(Doubler(5)) ' Display the double of 5
            Console.ReadLine() ' Wait for user input
        End Sub
    
        Function Doubler(ByVal num As Integer) As Integer
            Return num * 2 ' Return the entered number times by 2
        End Function
    End Module
    To call a function you don't need to write the value to the screen, you can just call it like so.
    Code:
    <Name>(<arguments>)
    A sub routine can be used in much the same way except you change Function to Sub.

    Lesson 6 - Variable Scope
    Variable Scope is an important part for variables, especially when you start using multiple functions. Variable Scope is a problem that many new programmers come into contact with. I often see on forums people posting a compile error like <Variable> is not declared, even when it is. This is because the function that they are trying to access the variable from doesn't have permissions.
    This means that if you declare a variable within another function it will not be accessable in others. Try this program and you will understand.
    Code:
    ' Lesson  6 - Variable Scope
    Module Lesson6
        Sub Main()
            Dim myAge As Integer
            myAge = 15
        End Sub
    
        Function DoubleAge()
            Return myAge * 2 ' DoubleAge function doesn't know of myAge variable
        End Function
    End Module
    You should recieve the following error.
    Error 1 Name 'myAge' is not declared. C:\Documents and Settings\FreckleS\Local Settings\Application Data\Temporary Projects\Lesson6\Module1.vb 9 16 Lesson6

    This is because the variable is declared with the function Main(). In order to use the variable in DoubleAge() function you would need to pass it as a argument or parameter or you can declare the function outside of any other function which makes it available to any function. I will demonstrate both options.

    Code:
    ' Lesson  6 - Variable Scope
    Module Lesson6
        Dim myAge As Integer
        Sub Main()
            myAge = 15
            Console.WriteLine(DoubleAge)
            Console.ReadLine()
        End Sub
    
        Function DoubleAge()
            Return myAge * 2 ' DoubleAge function doesn't know of myAge variable
        End Function
    End Module
    and

    Code:
    ' Lesson  6 - Variable Scope
    Module Lesson6
        Sub Main()
            Dim myAge As Integer
            myAge = 15
            Console.WriteLine(DoubleAge(myAge)) ' Pass myAge to DoubleAge function.
            Console.ReadLine()
        End Sub
    
        Function DoubleAge(ByVal num As Integer)
            Return num * 2 ' DoubleAge function doesn't know of myAge variable
        End Function
    End Module
    In the second example DoubleAge still doesn't know about myAge, all it knows is that its value (15) is passed to it as the num argument.

    Lesson 7 - Select Case Statements
    Remember the 3 control structures, Sequence, Selection, Repetition? Well these is If/Else statement's big brother. He can handle multiple selections with ease, much like if/else if/else. Although this can become cubersome with a large amount of selections, select case however...never

    The syntax for a Select Case Statement
    Code:
    Select Case <Expression>
        Case <Expression>
            <Statement>
        Case Else
            <Statement>
    End Select
    In my example I am just lazy so I didn't do all the options but you get the idea.
    Code:
    ' Lesson 7 - Select Case Statements
    Module Lesson7
        Sub Main()
            Dim myAge As Integer
            Console.WriteLine("Please enter my age: ")
            myAge = Console.ReadLine()
            Select Case myAge
                Case 1
                    Console.WriteLine("Im not 1")
                Case 2
                    Console.WriteLine("Im not 2")
                Case 3
                    Console.WriteLine("Im not 3")
                Case 15
                    Console.WriteLine("I am 15!")
                Case Else
                    Console.WriteLine("I handle exceptions like you!")
            End Select
            Console.ReadLine()
        End Sub
    End Module
    On Line 7 it sets up the statement. This would be the same as writing
    Code:
    ' Lesson 7 - Select Case Statements
    Module Lesson7
        Sub Main()
            Dim myAge As Integer
            Console.WriteLine("Please enter my age: ")
            myAge = Console.ReadLine()
            If myAge = 1 Then
                Console.WriteLine("Im not 1")
            ElseIf myAge = 2 Then
                Console.WriteLine("Im not 2")
            ElseIf myAge = 3 Then
                Console.WriteLine("Im not 3")
            ElseIf myAge = 15 Then
                Console.WriteLine("I am 15!")
            Else
                Console.WriteLine("I handle exceptions like you!")
            End If
            Console.ReadLine()
        End Sub
    End Module
    Even whilst I was writing that, small amount of selection I got bored with the if/else statements much before the select case statements.

    Lesson 8 - Arrays
    Arrays are a wonderful, powerful and mighty feature of Visual Basic. They allow you to store related information within the "same" variable.
    They are declared almost the same as a variable except that after the name you place brackets and the number of elements it can hold. In Visual Basic arrays are "Zero Based" which means the index starts at 0 so:
    Code:
            Dim customerNames(4) As String
    Creates an array which can hold 5 elements(0, 1, 2, 3 and 4).

    To assign an individual array you once again use almost the same syntax as for a variable.
    Code:
            customerNames(0) = "John Reed"
            customerNames(1) = "Jack Smith"
            customerNames(2) = "Ella Harper"
            customerNames(3) = "Max Johnson"
            customerNames(4) = "Samantha Pong"
    The following code is quite cubersome and you will learn how to improve on this method shortly.
    Code:
    ' Lesson 8 - Arrays
    Module Lesson8
        Sub Main()
            Dim customerNames(4) As String
            customerNames(0) = "John Reed"
            customerNames(1) = "Jack Smith"
            customerNames(2) = "Ella Harper"
            customerNames(3) = "Max Johnson"
            customerNames(4) = "Samantha Pong"
    
            Console.WriteLine(customerNames(0))
            Console.WriteLine(customerNames(1))
            Console.WriteLine(customerNames(2))
            Console.WriteLine(customerNames(3))
            Console.WriteLine(customerNames(4))
    
            Console.ReadLine() ' Wait for user input to exit.
        End Sub
    End Module
    Lesson 9 - Recursion & Loops
    The final control structure, Repetition.

    Repetition is a great feature of any programming language, it allows for things to do be done, a set number of times or an infinite number of times, however you should try to avoid this as it generally strains the CPU.

    There a few different types of loops.


    • Do...Until
    • Do...While
    • For Each...Next
    • Do...Loop



    Also in functions you can call the function from the same function which is called Recursion.

    A very basic loop is one that counts to 10.

    First you will need to declare a variable called "counter" as an integer.

    We will use either a Do Until or a Do While Loop, they achieve the same thing but have a slight difference in the expression.

    The syntax for a loop is generally.
    [code[
    Do Until <Expression>
    <Statements>
    Loop
    [/code]

    We will use a counter integer as the test expression. This basically sets our number of loops.

    Code:
    ' Lesson 9 - Recursion & Loops
    Module Lesson9
        Sub Main()
            Dim counter As Integer = 1 ' Declare counter variable as Integer and assign 1 to it.
            Do Until counter = 11 ' Loop until counter equals 11
                Console.WriteLine(counter) ' Print the current value of counter
                counter += 1 ' Increment counter
            Loop ' Go again
            Console.ReadLine() ' Wait for user input to exit.
        End Sub
    End Module
    This should give the output.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    Wonderful...Why doesn't it print out 11 though you ask. Well...The loop tells us.
    Code:
    Do Until counter = 11
    Until is the keyword there. Once it is equal to 11 it will not loop again and go to the next line of code after the loop.

    Similiarly. Do While loops work in much the same manner.

    Code:
    ' Lesson 9 - Recursion & Loops
    Module Lesson9
        Sub Main()
            Dim counter As Integer = 1 ' Declare counter variable as Integer and assign 1 to it.
            Do While counter <> 11 ' Loop until counter equals 11
                Console.WriteLine(counter) ' Print the current value of counter
                counter += 1 ' Increment counter
            Loop ' Go again
            Console.ReadLine() ' Wait for user input to exit.
        End Sub
    End Module
    That strange operator you see there "<>" is the not equals operator, or the Inequality Operator. Then you also all your normal maths crap, > greater than, < less than, >= greater than or equals to, <= less that or equals to.

    For Each...Next Loops as a wonderful loop that can be used to loop through something for a finite amount of times. Using an array is the perfect example so from the previous lesson.
    Code:
    ' Lesson 9 - Recursion & Loops
    Module Lesson9
        Sub Main()
            Dim customerNames(4) As String
            customerNames(0) = "John Reed"
            customerNames(1) = "Jack Smith"
            customerNames(2) = "Ella Harper"
            customerNames(3) = "Max Johnson"
            customerNames(4) = "Samantha Pong"
    
            For Each name As String In customerNames
                Console.WriteLine(name)
            Next
    
            Console.ReadLine() ' Wait for user input to exit.
        End Sub
    End Module
    Lesson 10 - Classes
    Classes are the building blocks to Object Orientated Programming (OOP). OOP is one of the main benefits of languages like Visual Basic and C++ over C and other languages. C is a structured language. OOP allows you to think about real world objects as if they were part of your computer. The world is filled with objects, cars, cats, dogs, trees, houses etc. These objects have characteristics, tall, brown, small, bark.

    OOP allows you to "import" these objects into your computer to manipulate. If you are looking for more information on OOP look up some C++ stuff. C++ was designed a bridge between C and OOP to bring the power of OOP to the commercial developer platform of C so there is plenty of resources about.

    Declaring a class is much like declaring a function or even a variable. It can also contain both of these.

    The syntax for declaring a class is.
    Class <Name>
    <Variables>
    <Functions>
    End Class

    I am going to use a Cat as an example.
    Code:
        Class Cat
            ' Declare variables
            Public itsAge As Integer = 3
            Public itsWeight As Integer = 20
    
            ' Create meow function
            Sub Meow()
                Console.WriteLine("Meooowww")
            End Sub
        End Class
    That is your class declared but now we want to use it. We need to create an object to be able to use it. In Main or whatever function you are in you can declare your object like so.
    Code:
    Dim <Object> As New Cat
    Code:
    Dim Jasper As New Cat ' Create a new object instance of Cat named Jasper
    Now you have a "working" Cat. To use the cat you can simply use the Object name followed by a period (.) then the member variable or member function or whatever.

    Code:
    ' Lesson 10 - Classes
    Module Lesson10
        Class Cat
            ' Declare variables
            Public itsAge As Integer = 3
            Public itsWeight As Integer = 20
    
            ' Create meow function
            Sub Meow()
                Console.WriteLine("Meooowww")
            End Sub
        End Class
    
        Sub Main()
            Dim Jasper As New Cat ' Create a new object instance of Cat named Jasper
            Console.WriteLine("Jasper weighs {0} and is {0} years old", Jasper.itsWeight, Jasper.itsAge) ' Get member variable info from the class
            Jasper.Meow() ' Make jasper meow.
            Console.ReadLine()
        End Sub
    End Module
    Believe it or not but you have been using OOP code since you started with that very first application, Hello World. When I mentioned member function of class with Console.ReadLine that is the exact same as this.
    Ours:
    Class = Cat
    Member Function = Meow

    Systems:
    Class = Console
    Member Function = ReadLine

    Amazing isn't it?

    Lesson 11 - File Manipulation
    File Manipulation is a very important part of programming, for me anyway. I like to often read values from text files and store data in them if I don't want to use registry or settings (don't worry).

    This Lesson is sort of a challenge. It will be short and sweet and as it is really a combination of some of the previous lessons hopefully you will be able to pick it up really easy.
    We need to import System.IO however which you may not have done before. This allows us to use code from the System.IO file. At the top of your workspace simply type.
    Code:
    Imports System.IO
    Now we can use may features from the System.IO dll. One of which is StreamReader and its brother StreamWriter. You guessed it, this allows us to read and write bytes with a certain encryption to a file of our choice.

    You need to create an object of the StreamReader class and then we need to read the file so check out the member function ReadToEnd(). The code I came up with is.
    Code:
    ' Lesson 11 - File Manipulation
    Imports System.IO ' We use this file to input/output files.
    Module Lesson11
        Sub Main()
            Console.WriteLine(ReadFile("C:\Testfile.txt"))
            WriteFile("C:\TestFile2.txt", "Hello there GREAT VB Coder!")
            Console.ReadLine()
        End Sub
    
        Function ReadFile(ByVal targetFile As String)
            Dim fileContents As String ' Declare variable
            Dim read As New StreamReader(targetFile) ' Create a new object of the Class StreamReader
            fileContents = read.ReadToEnd ' Assign the variable to the return value of the member function
            read.Close()
            Return fileContents ' Return the contents of the text file using a member function from StreamReader class
        End Function
    
        Function WriteFile(ByVal targetFile As String, ByVal text As String)
            Dim write As New StreamWriter(targetFile) ' Create a new object of the Class StreamWriter
            write.WriteLine(text)
            write.Close()
        End Function
    End Module
    Hopefully you got something very similiar if not better and hopefully you got it easily. A couple of attempts and you should have it perfect. Make sure that you close the file or you will get errors next time you try to use it.

    Lesson 12 - Try Catch Statements
    I somewhat forgot about this but its ok cause its back now. It wasn't really needed too bad previously but it would have done good in the previous example.

    The Try...Catch Statement is used catch exceptions that may occur whilst you are trying to do something. Usually something with a high chance of failing.

    If I was to use the same sort of thing on the previous example it would like this.
    Code:
    ' Lesson 12 - Try Catch Statements
    Imports System.IO
    Module Lesson12
    
        Sub Main()
            Try
                Console.WriteLine(ReadFile("C:\Testfile.txt"))
                WriteFile("C:\TestFile2.txt", "Hello there GREAT VB Coder!")
                Console.ReadLine()
            Catch ex As Exception ' Stops crashing
                Console.WriteLine(ex) ' Display exception
                Console.ReadLine()
            End Try
        End Sub
    
        Function ReadFile(ByVal targetFile As String)
            Dim fileContents As String ' Declare variable
            Dim read As New StreamReader(targetFile) ' Create a new object of the Class StreamReader
            fileContents = read.ReadToEnd ' Assign the variable to the return value of the member function
            read.Close()
            Return fileContents ' Return the contents of the text file using a member function from StreamReader class
        End Function
    
        Function WriteFile(ByVal targetFile As String, ByVal text As String)
            Dim write As New StreamWriter(targetFile) ' Create a new object of the Class StreamWriter
            write.WriteLine(text)
            write.Close()
        End Function
    End Module
    Delete the file "C:\Testfile.txt" and see what happens. You get this ugly long exception message. Since this is one of the most likely exceptions that occur we can count on that and make the handling a bit smoother, more user friendly.

    Code:
    ' Lesson 12 - Try Catch Statements
    Imports System.IO
    Module Lesson12
    
        Sub Main()
            Try
                Console.WriteLine(ReadFile("C:\Testfile.txt"))
                WriteFile("C:\TestFile2.txt", "Hello there GREAT VB Coder!")
                Console.ReadLine()
            Catch ex As FileNotFoundException ' Stops crashing when file isn't found
                Console.WriteLine("File not found!") ' Display exception
                Console.ReadLine()
            End Try
        End Sub
    
        Function ReadFile(ByVal targetFile As String)
            Dim fileContents As String ' Declare variable
            Dim read As New StreamReader(targetFile) ' Create a new object of the Class StreamReader
            fileContents = read.ReadToEnd ' Assign the variable to the return value of the member function
            read.Close()
            Return fileContents ' Return the contents of the text file using a member function from StreamReader class
        End Function
    
        Function WriteFile(ByVal targetFile As String, ByVal text As String)
            Dim write As New StreamWriter(targetFile) ' Create a new object of the Class StreamWriter
            write.WriteLine(text)
            write.Close()
        End Function
    End Module
    Lesson 13 - Data Type Conversion
    Sometimes you might need data as a specific data type. Somebody might try to be smart and enter a double when you ask for an integer or something like that.

    In Visual Basic there are two types of Data Type Conversion, Implicity and Explicity. Implicity means that you do the conversion yourself. You don't actually convert but you store a value as the "wrong" data type and it will lose data.
    An example.
    Code:
    ' Lesson 13 - Data Type Conversion
    Module Lesson13
        Sub Main()
            Dim doub As Double = 15.723
            Dim int As Integer
            int = doub ' Integer is a whole number
            Console.WriteLine(int)
            Console.ReadLine()
        End Sub
    End Module
    Since an Integer data type is a whole number the output will be 16. The compiler will round doub up.

    Explicity means that the data will automatically be converted.
    Visual Basic comes with a class called CType. It is a cast and the above example would like this this.
    Code:
    ' Lesson 13 - Data Type Conversion
    Module Lesson13
        Sub Main()
            Dim doub As Double = 15.723
            Dim int As Integer
            int = CType(doub, Integer) ' Convert to integer
            Console.WriteLine(int)
            Console.ReadLine()
        End Sub
    End Module
    Or we could also use CInt which is the cast type of int.
    Code:
    ' Lesson 13 - Data Type Conversion
    Module Lesson13
        Sub Main()
            Dim doub As Double = 15.723
            Dim int As Integer
            int = CInt(doub)
            Console.WriteLine(int)
            Console.ReadLine()
        End Sub
    End Module
    Other data type conversion functions in Visual Basic include:
    Function, Use
    CBool, Convert to Boolean Data Type
    CByte, Convert to Byte Data Type
    CDate, Convert to Date Data Type
    CSng, Convert to Single Data Type
    CShort, Convert to Short Data Type
    CInt, Convert to Integer Data Type
    CLng, Convert to Long Data Type
    CDbl, Convert to Double Data Type
    CDec, Convert to Decimal Data Type
    CObj, Convert to Object Data Type
    CString, Convert to String Data Type
    CChar, Convert to Char Data Type

    Lesson 14 - Enumeration
    Enumeration is the use of a related set of constants, it is similiar to Classes but not quite as cool. The problem with enumeration is that you are working with constants, this is of course good in some instances but I prefer to work with classes, do as you wish. Fine...Ill teach you both.

    You can declare an enumerated type with the following syntax.
    Code:
    Enum <Name>
    <Constants>
    End Enum
    Then the same as classes you can reference your constants with the Enum name followed by a period (.) then the constant.

    Code:
    ' Lesson 14 - Enumeration
    Module Lesson14
        Enum Colours
            red = 1
            green = 2
            blue = 3
        End Enum
        Sub Main()
            Console.WriteLine("Red is the number " & Colours.red & " colour")
            Console.ReadLine()
        End Sub
    End Module
    Lesson 15 - Multithreading
    Multithreading is one of the most important parts of software developement. For me anyway. A lot of software is going to need to be able to do several things at once or a couple of high CPU or time consuming tasks at the same time. If your application is running on a single thread and you want to do a couple of these tasks at once then your program will lag.

    I will use the example of downloading a file from my website. First you must import the .dll System.Threading. So at the very top of your page:
    Code:
    Import System.Threading
    You also must create a new function that will contain your code to download the file, or whatever it is you are making.

    Now as you should know by now, we can now use its member functions of the System.Threading Class. But as again you should know by now we have to create an object instance of it so we can use it.
    Code:
        Dim myThread As New Thread(AddressOf DownloadFile)
    A member function of the Thread class is Start. What do you think that does? Use it when you want to use your function.

    Code:
    ' Lesson 15 - Multithreading
    Imports System.Threading
    Module Lesson15
        Dim myThread As New Thread(AddressOf DownloadFile)
        Sub Main()
            Console.WriteLine("Single thread.")
            myThread.Start() ' Start the new thread
            Console.WriteLine("Don't have to wait for it to finish!")
            Console.ReadLine()
        End Sub
    
        Function DownloadFile()
            Try
                My.Computer.Network.DownloadFile("http://gamesalter.com/freckles/coding/Banned.exe", "C:\lol.exe")
                Console.WriteLine("Finished download!")
                myThread.Abort() ' Cancel the thread to avoid excess CPU usage.
            Catch ex As Exception
                Console.WriteLine(ex)
            End Try
        End Function
    End Module
    You should also remember to use the member function Abort() when you are finished with your thread as it will give the CPU a break.

    A couple more member functions of the Thread Class include:

    • Sleep
    • Resume
    • Suspend



    You can also set the priority of threads just like you can to processes in Task Manager.

    Priority = ThreadPriority.Highest

    The list of priorities include:

    • Lowest
    • Below Normal
    • Normal
    • Above Normal
    • Highest



    I think your done. Now here is some useful code snippets that you can use just give credits to me.

    Custom CopyFile Class
    Code:
    Imports System.IO
    
    Module CopyFileClass
    
        Sub Main()
            Console.Title = "Custom CopyFile Class"
    
            Dim strSrcFile, strDestFile As String
            Console.WriteLine("Please Enter Source File: ")
            strSrcFile = Console.ReadLine()
    
            Console.WriteLine("Please Enter Destination File: ")
            strDestFile = Console.ReadLine()
    
            CopyFile(strSrcFile, strDestFile)
        End Sub
    
        Sub CopyFile(ByVal SrcFile As String, ByVal DestFile As String)
            Try
                File.WriteAllBytes(DestFile, File.ReadAllBytes(SrcFile))
            Catch ex As Exception
                Console.WriteLine(ex.Message)
                Console.ReadLine()
                Exit Sub
            End Try
            Console.WriteLine(vbCrLf & "Successfully Copied {0} To {1}", SrcFile, DestFile)
            Console.ReadLine()
        End Sub
    End Module
    Recursive File Search
    Code:
    Imports System.IO
    Module Module1
        Sub Main()
            Search("C:\") ' Which directories to search
            Console.ReadLine() ' Display Output
        End Sub
    
        Sub Search(ByVal directoryPath)
            Dim files() As String ' Unset array of files
            Dim directories() As String ' Unset array of directories
    
            files = Directory.GetFiles(directoryPath) ' Load all files
            For Each File In files ' Each file
                Console.WriteLine(File)
            Next ' Get the next file
    
            directories = Directory.GetDirectories(directoryPath) ' Load all the sub directories
            For Each Directory In directories ' Each directory/sub directory
                Console.WriteLine(Directory) ' This will write the directory (not needed but you can use)
                Search(Directory) ' Go again in new directory
            Next ' Get the next directory
        End Sub
    End Module
    Basic Anti-Leak Protection
    Code:
    Imports System.Management
    
    Module AntiLeak
        Sub Main()
            ALP()
        End Sub
    
        Friend Function GetVolumeSerial(Optional ByVal strDriveLetter As String = "C") As String
            Dim hds As ManagementObject = New ManagementObject(String.Format("win32_logicaldisk.deviceid=""{0}:""", strDriveLetter))
            hds.Get()
            Return hds("VolumeSerialNumber").ToString()
        End Function
    
        Private Sub ALP()
            Select Case (GetVolumeSerial())
                Case Is = "58057611"
                    MessageBox.Show("Anti-Leak Protection Passed" & vbCrLf & "Welcome Jarrad Freck - Creator", "Success")
                Case Is = "F85A4208"
                    MessageBox.Show("Anti-Leak Protection Passed" & vbCrLf & "Welcome Jean Doe - Customer", "Success")
                Case Is = "C457CD21"
                    MessageBox.Show("Anti-Leak Protection Passed" & vbCrLf & "Welcome John Smith - Beta Tester", "Success")
                Case Else
                    MessageBox.Show("Anti-Leak Protection Failed", "Failed")
                    Application.Exit()
            End Select
        End Sub
    End Module
    Yeah thats enough code, you can also learn a bit by studying these codes.

    By reading ALL of this doesn't make you a Visual Basic programmer, it gives you a good step into the language however. There are thousands of resources out there and in time you will become better and better just keep practicing and coding. The best way to learn is by doing.

    Credits:

    • FreckleS
    • reddy <3
    • GamesAlter.com
    • Pro9ramming.com
    • Aimbots.net
    • Removed for ^^



    This tutorial may not be distributed without my permission, ask me if you would like to and chances are I will let you. Do the right thing by me and I will return the favour.

    If people find that I have done something wrong please let me know, I am not perfect and this has really taken it out of me. I know that I haven't explained everything perfectly and if you would clarification ask. Or contact me at:
    Email: freckles@abclan.net or codeducks@gmail.com
    MSN: freckles@muppetalert.com
    Xfire: freckles123
    Steam: Code_Ducks
    PM: At any of the above listed sites.

    Have fun!

    Source Codes Attached to Thread
    Attached Files Attached Files
    "The pain you feel today, will be the strength you feel tomorrow"

Similar Threads

  1. Visual C++ And Visual Basic Aimbot?
    By iamacheater1 in forum Basics
    Replies: 7
    Last Post: July 6th, 2009, 06:07
  2. Replies: 5
    Last Post: January 11th, 2008, 00:27
  3. Replies: 7
    Last Post: October 5th, 2007, 06:46
  4. [TUTORIAL]Visual Basic[BASIC]
    By FreckleS in forum Basics
    Replies: 0
    Last Post: October 5th, 2007, 04:37

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •