Sunday, 23 February 2014

The MDI NotePad Application


The MDI NotePad sample application is a simple text editor similar to the NotePad application included with Microsoft Windows. The MDI NotePad application, however, uses a multiple-document interface (MDI). At run time, when the user requests a new document (implemented with the New command on the application's File menu), the application creates a new instance of the child form. This allows the user to create as many child forms, or documents, as necessary.
To create a document-centered application in Visual Basic, you need at least two forms — an MDI form and a child form. At design time, you create an MDI form to contain the application and a single child form to serve as a template for the application's document.
To create your own MDI NotePad application
  1. From the File menu, choose New Project.
  2. From the Project menu, choose Add MDI Form to create the container form.
    The project should now contain an MDI form (MDIForm1) and a standard form (Form1).
  3. Create a text box (Text1) on Form1.
  4. Set properties for the two forms and the text box as follows.
    Object Property Setting
    MDIForm1 Caption MDI NotePad
    Form1 Caption
    MDIChild
    Untitled
    True
    Text1 MultiLine
    Text
    Left
    Top
    True
    (Empty)
    0
    0

  5. Using the Menu Editor (from the Tools menu), create a File menu for MDIForm1.
    Caption Name Indented
    &File mnuFile No
    &New mnuFileNew Yes

  6. Add the following code to the mnuFileNew_Click procedure:
    Private Sub mnuFileNew_Click ()
        ' Create a new instance of Form1, called NewDoc.
        Dim NewDoc As New Form1
        ' Display the new form.
        NewDoc.Show
    End Sub
    
    This procedure creates and then displays a new instance (or copy) of Form1, called NewDoc. Each time the user chooses New from the File menu, an exact duplicate (instance) of Form1 is created, including all the controls and code that it contains.
  7. Add the following code to the Form_Resize procedure for Form1:
    Private Sub Form_Resize ()
        ' Expand text box to fill the current child form.
        Text1.Height = ScaleHeight
        Text1.Width = ScaleWidth
    End Sub
    
    The code for the Form_Resize event procedure, like all the code in Form1, is shared by each instance of Form1. When several copies of a form are displayed, each form recognizes its own events. When an event occurs, the code for that event procedure is called. Because the same code is shared by each instance, you might wonder how to reference the form that has called the code — especially since each instance has the same name (Form1). This is discussed in "Working with MDI Forms and Child Forms," later in this chapter.
  8. Press F5 to run the application.

Creating an MDI Application

Use the following procedure to create an MDI form and its child forms.
To create an MDI application
  1. Create an MDI form.
    From the Project menu, choose Add MDI Form.
    Note   An application can have only one MDI form. If a project already has an MDI form, the Add MDI Form command on the Project menu is unavailable.
  2. Create the application's child forms.
    To create an MDI child form, create a new form (or open an existing one) and set its MDIChild property to True.

Run-Time Features of MDI Forms


At run time, an MDI form and all of its child forms take on special characteristics:
  • All child forms are displayed within the MDI form's workspace. The user can move and size child forms like any other form; however, they are restricted to this workspace.
  • When a child form is minimized, its icon appears on the MDI form instead of the taskbar. When the MDI form is minimized, the MDI form and all of its child forms are represented by a single icon. When the MDI form is restored, the MDI form and all the child forms are displayed in the same state they were in before being minimized.
  • When a child form is maximized, its caption is combined with the caption of the MDI form and is displayed in the MDI form's title bar (see Figure 6.6).
  • By setting the AutoShowChildren property, you can display child forms automatically when forms are loaded (True), or load child forms as hidden (False).
  • The active child form's menus (if any) are displayed on the MDI form's menu bar, not on the child form.
    Figure 6.6   A child form caption combined with the caption of an MDI form

MDI Child Forms at Design Time


At design time, child forms are not restricted to the area inside the MDI form. You can add controls, set properties, write code, and design the features of child forms just as you would with any other Visual Basic form.
You can determine whether a form is an MDI child by looking at its MDIChild property, or by examining the Project Explorer. If the form's MDIChild property is set to True, it is a child form. Visual Basic displays special icons in the Project Explorer for the MDI and MDI child forms, as shown in Figure 6.5.
Figure 6.5   Icons in the Project Explorer identify MDI child, standard, and MDI forms

Multiple-Document Interface (MDI) Applications


The multiple-document interface (MDI) allows you to create an application that maintains multiple forms within a single container form. Applications such as Microsoft Excel and Microsoft Word for Windows have multiple-document interfaces.
An MDI application allows the user to display multiple documents at the same time, with each document displayed in its own window. Documents or child windows are contained in a parent window, which provides a workspace for all the child windows in the application. For example, Microsoft Excel allows you to create and display multiple-document windows of different types. Each individual window is confined to the area of the Excel parent window. When you minimize Excel, all of the document windows are minimized as well; only the parent window's icon appears in the task bar.
A child form is an ordinary form that has its MDIChild property set to True. Your application can include many MDI child forms of similar or different types.
At run time, child forms are displayed within the workspace of the MDI parent form (the area inside the form's borders and below the title and menu bars). When a child form is minimized, its icon appears within the workspace of the MDI form instead of on the taskbar, as shown in Figure1

Figure 1   Child forms displayed within the workspace of the MDI form

Date and Time Functions


CDate([expr]): Converts a valid date and time expression to a date variable

Example:
' declare a date variable.
Dim curDate as Date
' set our date variable
curDate = CDate("May 20, 2011")
' curDate contains the date using VB's internal storage formats for date/time.
curDate = CDate("2:45:00 PM")
' curDate now contains the time with today's date.
curDate = CDate("May 20, 2011 2:45:00 PM")
' curDate now contains the date and time specified.

IsDate([expr]): Returns a Boolean value that indicates if the evaulated expression can be converted to a date.

Example:
' declare variables.
Dim myDate as Boolean
' set our date variable
myDate = IsDate("May 20, 2011")
' myDate = True
myDate = IsDate(#05/20/2011#)
' myDate = True
myDate = IsDate("5/20/2011")
' myDate = True
myDate = IsDate("52/20/2011")
' myDate = False
myDate = IsDate("Hello World!")
' myDate = False

FormatDateTime([date], [format]) : Returns date or time in a specified format
[format] can take the following values:
  • 0 = vbGeneralDate - Defualt, Returns date: mm/dd/yy and time if specified: hh:mm:ss am/pm.
  • 1 = vbLongDate - Returns date: weekday, monthname, year
  • 2 = vbShortDate - Returns date: mm/dd/yy
  • 3 = vbLongTime - Returns time: hh:mm:ss am/pm
  • 4 = vbShortTime - Returns time: hh:mm
Some may choose to use the Format() function instead because you can be more specific with the format you want

Now(): Returns the current system date and time

Example:
' declare a date variable.
Dim curDate as Date
' set our date variable
curDate = Now()
' VB will automatically convert from date to string.
MsgBox(curDate)
' Produces a message box with the current date and time.

String Functions


CStr([expr]) :Converts a variable expression to a string

Example:
' declare a date variable.
Dim curDate as Date
' set our date variable to the current date/time.
curDate = Now()
' MsgBox expects a string so we need to convert our date.
MsgBox(CStr(curDate))
' Produces a message box with the current date and time.

LCase([string])
UCase([string]) :Converts a string to lower case (or upper case with UCase() function.)

Example:
' declare variables.
Dim txt as Date
txt = "This is a beautiful day!"
txt = UCase(txt)
' txt = "THIS IS A BEAUTIFUL DAY!".
txt = LCase(txt)
' txt = "this is a beautiful day!".

Left([string], [length])
Right([string], [length]) : Returns a specific number of characters from the left side (right side with the Right() Function) of a string

Example:
' declare variables.
Dim txt as Date
txt = "This is a beautiful day!"
txt = Left(txt, 6)
' txt = "This i".
txt = Right(txt, 2)
' txt = " i".

Len([string])):Returns the number of characters in a string

Example:
' declare variables.
Dim txt as String
Dim cnt as Integer
txt = "This is a beautiful day!"
cnt = Len(txt)
' cnt = 24
cnt = Len("This is a beautiful day!")
' cnt = 24

 Mid([string], [start], [length])):Returns a specified number of characters from a string

Example:
' declare variables.
Dim txt as String
Dim txt2 as Integer
txt = "This is a beautiful day!"
txt2 = Mid(txt, 1, 1)
' txt2 = "T"
txt2 = Mid(txt, 3, 10)
' txt2 = "is is a be"


Trim([string])
LTrim([string])
RTrim([string])
Remove spaces from both sides of a string. (LTrim = left side only, RTrim = right side only)

Example:
' declare variables.
Dim fname as Date
Dim txt as Date
fname = " Tim "
txt = "Hello" & fname & "and welcome"
' txt = "Hello Tim and welcome".
txt = "Hello" & Trim(fname) & "and welcome"
' txt = "HelloTimand welcome".

InStr([start], [string1], [string2], [compare])
InStrRev([start], [string1], [string2], [compare]):
Returns the position of the first (or last with InStrRev) occurance of one string within another.
[compare] can have a value of 0 = vbBinaryCompare or 1 = vbTextCompare

Example:
' declare a string variable and integer variable.
Dim txt as String
Dim pos as Integer
txt = "This is a beautiful day!"
pos = InStr(0, txt, "beautiful")
' pos = 10.

FindReplace(sSearchString$, sFindWhat$, sReplaceWith$):
This function is not a built in function to VB however can be very useful in your VB applications. A simple search and replace function. Pass sSearchString$ ByRef.

Math Functions


Abs([expr]))
Returns the absolute value of a specified expression.
Example:
' declare as double so the variable can store a decimal portion of a number.
Dim myNumb as Double
myNumb = Abs(3.14159)
' myNumb = 3
myNumb = Abs(-42)
' myNumb = 42


Int([expr]))
Fix([expr]))
Returns the integer part of a specified expression. the Fix() function does exactly the same as Int()
 

Example:
' declare as double so the variable can store a decimal portion of a number.
Dim myNumb as Double
myNumb = 3.14159
myNumb = Int(myNumb)
' myNumb now = 3


Randomize()
Rnd([number])
Generate a random number. The number is always less than 1 but greater than 0.
The [number] field is optional. the [number] field is to seed the random number generator. use Randomize() to generate a random seed. setting the [number] field will generate the same set of random numbers each time Rnd() is called.
 

Example: (this could be made to a function of it's own)
' declare variables.
Dim min as Integer
Dim max as Integer
Dim rNumb as Integer
' set our variables
min = 1
max = 100
' generate random seed.
Randomize
' generate a random number.
rNumb = Int((max - min + 1) * Rnd() + min)
' rNumb now contains a random number between 1 and 100.


Sqr([number]))
Returns the square root of number.
 

Example:
' declare the variable.
Dim myNumb as Double
myNumb = Sqr(9)
' myNumb = 3
myNumb = Sqr(47)
' myNumb = 6.85565460040104


Cos([angle]))
Sin([angle]))
Tan([angle]))
Atn([angle]))
Geomotry functions to calculate Cosine, Sine, Tangent, and Arctangent.

Operators

An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data.
We have several types of operators:
  • Arithmetic operators
  • Boolean operators
  • Relational operators
  • Bitwise operators
An operator may have one or two operands. An operand is one of the inputs (arguments) of an operator. Those operators that work with only one operand are called unary operators. Those who work with two operands are called binary operators.
Option Strict On

Module Example

    Sub Main()

        Print(2)
        Print(-2)
        Print(2+2)
        Print(2-2)

    End Sub

End Module
+ and - signs can be addition and subtraction operators as well as unary sign operators. It depends on the situation.
Option Strict On

Module Example

    Dim a As Byte

    Sub Main()

        a = 1
        Print(-a)    ' Prints -1
        Print(-(-a)) ' Prints 1

    End Sub

End Module
The plus sign can be used to indicate that we have a positive number. But it is mostly not used. The minus sign changes the sign of a value.
Option Strict On


Module Example

    Dim a As Byte
    Dim b As Byte

    Sub Main()

        a = 3 * 3
        b = 2 + 2   
        
        Print(a) ' Prints 9
        Print(b) ' Print 4

    End Sub

End Module
Multiplication and addition operators are examples of binary operators. They are used with two operands.

The assignment operator

The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.
x = 1
        Print(x) ' Prints 1
Here we assign a number to the x variable.
x = x + 1
        Print(x)
The previous expression does not make sense in mathematics. But it is legal in programming. The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x.
3 = x
This code example results in syntax error. We cannot assign a value to a literal.

Arithmetic operators

The following is a table of arithmetic operators in Visual Basic.
SymbolName
+Addition
-Subtraction
*Multiplication
/Division
\Integer Division
ModModulo
^Exponentiation
The following example shows arithmetic operations.
Option Strict On


Module Example

    Dim a As Byte
    Dim b As Byte
    Dim c As Byte

    Dim add As Byte
    Dim sb As Byte
    Dim mult As Byte
    Dim div As Byte

    Sub Main()

        a = 10
        b = 11
        c = 12

        add = a + b + c
        sb = c - a
        mult = a * b
        div = CType(c / 3, Byte)
        
        Print(add)
        Print(sb)
        Print(mult)
        Print(div)

    End Sub

End Module
In the preceding example, we use addition, subtraction, multiplication and division operations. This is all familiar from the mathematics.
33
2
110
4
Output of the example.
Next we will show the distinction between normal and integer division.
Option Strict On


Module Example

    Dim a As Single = 5
    Dim b As Single = 2
    Dim c As Single

    Sub Main()

        c = 5 / 2 
        Print(c)
        c = 5 \ 2
        Print(c)
        
    End Sub

End Module
In the preceding example, we divide two numbers using normal and integer division operator. Visual Basic has two distinct operators for division.
Dim a As Single = 5
We use floating point data types.
c = 5 / 2 
        Print(c)
This is the 'normal' division operation. It returns 2.5, as expected.
c = 5 \ 2
        Print(c)
This is integer division. The result of this operation is always and integer. The c variable has value 2.
 
2.5
2
Result of the division

The last two operators that we will mention are modulo operator and exponentiation operator.
        Print(9 Mod 4) ' Prints 1
The Mod operator is called the modulo operator. It finds the remainder of division of one number by another. 9 Mod 4, 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1. Modulo operator can be handy for example when we want to check for prime numbers.
Finally, we will mention exponentiation operator.
        Print(9 ^ 2) ' Prints 81
9 ^ 2 = 9 * 9 = 81

Concatenating strings

In Visual Basic we have two operators for string concatenation. The plus + operator and the & ampersand operator.
Option Strict On


Module Example

    Sub Main()

              Print("Return " & "of " & "the king")
                Print("Return " + "of " + "the king")

    End Sub

End Module
We join three strings together using both operators.
Return of the king
Return of the king
 
And this is, what we get. Same result for both cases.

Boolean operators

In Visual Basic, we have the following logical operators. Boolean operators are also called logical.
SymbolName
Andlogical conjunction
AndAlsoshort circuit And
Orlogical inclusion
OrElseshort circuit Or
Xorlogical inclusion
Notnegation
Boolean operators are used to work with truth values.
Option Strict On


Module Example

    Dim x As Byte = 3
    Dim y As Byte = 8

    Sub Main()

        Print(x = y) 
        Print(y > x)

        If (y > x)
        Print("y is greater than x")
        End If

    End Sub

End Module
Many expressions result in a boolean value. Boolean values are used in conditional statements.
        Print(x = y) 
        Print(y > x)
Relational operators always result in a Boolean value. These two lines print False and True.
If (y > x)
        Print("y is greater than x")
End If
The body of the If statement is executed only if the condition inside the parentheses is met. The x > y returns True, so the message "y is greater than x" is printed to the terminal.
Option Strict On


Module Example

    Dim a As Boolean
    Dim b As Boolean
    Dim c As Boolean
    Dim d As Boolean

    Sub Main()

        a = (True And True)
        b = (True And False)
        c = (False And True)
        d = (False And False)

        Print(a)
        Print(b)
        Print(c)
        Print(d)


    End Sub

End Module
Example shows the logical And operator. It evaluates to True only if both operands are True.
True
False
False
False

The logical Xor operator evaluates to True, if exactly one of the operands is True.
Option Strict On


Module Example

    Dim a As Boolean
    Dim b As Boolean
    Dim c As Boolean
    Dim d As Boolean

    Sub Main

        a = (True Xor True)
        b = (True Xor False)
        c = (False Xor True)
        d = (False Xor False)

        Print(a)
        Print(b)
        Print(c)
        Print(d)

    End Sub

End Module
The logical Xor evaluates to False, if both operands are True or both False.
False
True
True
False

The logical Or operator evaluates to True, if either of the operands is True.
Option Strict On


Module Example

    Sub Main()

        Dim a As Boolean = True Or True
        Dim b As Boolean = True Or False
        Dim c As Boolean = False Or True
        Dim d As Boolean = False Or False

        Print(a)
        Print(b)
        Print(c)
        Print(d)

    End Sub

End Module
If one of the sides of the operator is True, the outcome of the operation is True.
True
True
True
False

The negation operator Not makes True False and False True.
Option Strict On


Module Example

    Sub Main(
)
        Print(Not True)
        Print(Not False)
        Print(Not (4 < 3))

    End Sub

End Module
The example shows the negation operator in action.
False
True
True


Relational Operators

Relational operators are used to compare values. These operators always result in a boolean value.
SymbolMeaning
<less than
<=less than or equal to
>greater than
>=greater than or equal to
==equal to
<>not equal to
Iscompares references
Relational operators are also called comparison operators.
        Print(3 < 4) ' Prints True
        Print(3 = 4) ' Prints False
        Print(4 >= 3) ' Prints True
As we already mentioned, the relational operators return boolean values. Note that in Visual Basic, the comparison operator is (=). Not (==) like in C and C influenced languages.
Notice that the relational operators are not limited to numbers. We can use them for other objects as well. Although they might not always be meaningful.
Option Strict On


Module Example


    Sub Main()

        Print("six" = "six") ' Prints True
        '        Print("a" > 6) 'this would throw
                                     ' an exception 
                Print("a" < "b") ' Prints True

    End Sub

End Module
We can compare string objects too. Comparison operators in a string context compare the sorting order of the characters.
        Print("a" < "b") ' Prints True
What exactly happens here? Computers do not know characters or strings. For them, everything is just a number. Characters are special numbers stored in specific tables. Like ASCII.
Option Strict On

Module Example

    Sub Main()

        Print("a" < "b")
        
        Print("a is: {0}",  Asc("a"))
        Print("b is: {0}",  Asc("b"))
        
    End Sub

End Module
Internally, the a and b characters are numbers. So when we compare two characters, we compare their stored numbers. The built-in Asc function returns the ASCII value of a single character.
True
a is: 97
b is: 98
In fact, we compare two numbers. 97 with 98.
        Print("ab" > "aa") ' Prints True
Say we have a string with more characters. If the first characters are equal, we compare the next ones. In our case, the b character at the second position has a greater value than the a character. That is why "ab" string is greater than "aa" string. Comparing strings in such a way does not make much sense, of course. But it is technically possible.
Finally, we will mention the Is operator. The operator checks if two object references refer to the same object. It does not perform value comparisons.
Option Strict On


Module Example

    Sub Main()

        Dim o1 As Object = New Object
        Dim o2 As Object = New Object
        Dim o3 As Object 
        
        o3 = o2

        Print(o1 Is o2)
        Print(o3 Is o2)

    End Sub

End Module
We create three objects and compare them with the Is operator.
Dim o1 As Object = New Object
Dim o2 As Object = New Object
We declare and initialize two Object instances. The Object class is a base class for all classes in the .NET framework. We will describe it later in more detail.
Dim o3 As Object 
The third variable is only declared.
o3 = o2
The o3 now refers to the o2 object. They are two references to the same object.
Console.WriteLine(o1 Is o2)
Console.WriteLine(o3 Is o2)
In the first case, we get False. o1 and o2 are two different object. In the second case, we get True. o3 and o2 refer to the same object.

Bitwise operators

Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal or hexadecimal symbols are only notations of the same number. Bitwise operators work with bits of a binary number. Bitwise operators are seldom used in higher level languages like Visual Basic.
SymbolMeaning
Notbitwise negation
Xorbitwise exclusive or
Andbitwise and
Orbitwise or
The bitwise negation operator changes each 1 to 0 and 0 to 1.
        Print(Not 7)  ' Prints -8
        Print(Not -8) ' Prints 7
The operator reverts all bits of a number 7. One of the bits also determines, whether the number is negative or not. If we negate all the bits one more time, we get number 7 again.
The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.
      00110
  And 00011
   =  00010
The first number is a binary notation of 6. The second is 3. The result is 2.
        Print(6 And 3) ' Prints 2
        Print(3 And 6) ' Prints 2
The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if either of the corresponding bits in the operands is 1.
     00110
  Or 00011
   = 00111
The result is 00110 or decimal 7.
        Print(6 Or 3) ' Prints 7
        Print(3 Or 6) ' Prints 7
The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.
      00110
  Xor 00011
   =  00101
The result is 00101 or decimal 5.
v(6 Xor 3) ' Prints 5

Compound assignment operators

The compound assignment operators consist of two operators. They are shorthand operators.
Option Strict On

Module Example

    Dim a As Integer

    Sub Main

        a = 1
        a = a + 1
        Print(a) ' Prints 2

        a += 1
        Print(a) ' Prints 3

    End Sub

End Module
The += compound operator is one of these shorthand operators. They are less readable than the full expressions but experienced programmers often use them.
Other compound operators are:
-=   *=   \=   /=   &=  ^= 

Subroutines and Functions

We use proceduresie, subroutines and functions to create modular programs. Visual Basic statements are grouped in a block enclosed by Sub, Function and matching End statements. The difference between the two is that functions return values, subroutines don't.
A procedure (subroutines and function) is a piece of code in a larger program. They perform a specific task. The advantages of using procedures(subroutines and functions) are:
  • Reducing duplication of code
  • Decomposing complex problems into simpler pieces
  • Improving clarity of the code
  • Reuse of code
  • Information hiding

Subroutines

A subroutines is a block of Visual Basic statements inside Sub, End Sub statements. Subroutines do not return values.
Option Strict On


Module Example

    Sub Main()
       
        SimpleSubroutine()
        
    End Sub
    
    Sub SimpleSubroutine()
        Print ("Simple subroutines")
    End Sub
    
End Module
This example shows basic usage of subroutines. In our program, we have two subroutines. The Main() procedure and the user defined SimpleSubroutines(). As we already know, the Main() subroutines is the entry point of a Visual Basic program.
SimpleSubroutines()
Each procedure has a name. Inside the Main() procedure, we call our user defined SimpleSubroutine() procedure.
Sub SimpleSubroutine()
    Console.WriteLine("Simple procedure")
End Sub



Procedures can take optional parameters.

 
Option Strict On

Module Example

    Sub Main()

        Dim x As Integer = 55
        Dim y As Integer = 32
       
        Addition(x, y)
        
    End Sub
    
    Sub Addition(ByVal k As Integer, ByVal l As Integer)
        Print(k+l)
    End Sub
    
End Module
In the above example, we pass some values to the Addition() procedure.
Addition(x, y)
Here we call the Addition() procedure and pass two parameters to it. These parameters are two Integer values.
Sub Addition(ByVal k As Integer, ByVal l As Integer)
    Print(k+l)
End Sub



Functions

A function is a block of Visual Basic statements inside Function, End Function statements. Functions return values.
There are two basic types of functions. Built-in functions and user defined ones. The built-in functions are part of the Visual Basic language. There are various mathematical, string , Date and time functions.

Option Strict On


Module Example

    Dim x As Integer = 55
    Dim y As Integer = 32
    
    Dim result As Integer

    Sub Main()

        result = Addition(x, y)
        Print (Addition(x, y))
        
    End Sub
    
    Function Addition(ByVal k As Integer,ByVal l As Integer) As Integer
        Return k+l
    End Function
    
End Module
Two values are passed to the function. We add these two values and return the result to the Main() function.
result = Addition(x, y)
Addition function is called. The function returns a result and this result is assigned to the result variable.