Unit 2
Unit 2
It offers a convenient and consistent way to group commands and an easy for users to access
them. Visual Basic provides an easy way to create menus with the modal Menu Editor dialog.
Basically, each menu item has a Caption property (possibly with an embedded & character to
create an access key) and a Name. Each item also exposes three Boolean properties, Enabled, Visible,
and Checked, which can be set both at design time and at run time.
At design time, you can assign the menu item a shortcut key so that your end users don't have
to go through the menu system each time they want to execute a frequent command.
An expanded menu
48
One of the most annoying defects of the Menu Editor tool is that it doesn't permit you to reuse
the menus you have already written in other applications.
The programmer can create menu control arrays. The Index TextBox specifies the menu's
index in the control array.The Menu Editor dialog also provides several CheckBoxes to control the
appearance of the Menu.
Checked: This is unchecked by default and allows the programmer the option of creating a checked
menu item( a menu item that act as a toggle and displays a check mark when selected. The following
is a Check Menu items.
Enabled : specifies whether a menu is disabled or not. If you see a disabled command in a menu that
means that feature is not available. The Visible checkbox specifies whether the menu is visible or not.
To add commands to the Form's menu bar, enter a caption and a name for each command. As
soon as you start typing the command's caption, it also appears in a new line in the list at the bottom
of the Menu Editor window. To add more commands click Enter and type the Caption and the Name.
Creating Menus
Open a new Project and save the form as menu.frm and save the project as menu.vbp.
Choose Tools ››› Menu Editor and type the menu items as shown below.
Caption Name
File mnuFile
Open mnuOpen
Save mnuSave
Exit mnuExit
Edit mnuEdit
49
Copy mnuCopy
Cut mnuCut
Paste mnuPaste
Run the application by pressing F5. You can see that you can select a menu.
Application Standardization includes the structure of your toolbars, menus, and overall look
and feel of your applications. All Windows applications look similar, and yours should be designed to
enable the users to learn the application quickly. For example: Most Windows applications have a
File menu dealing with file-oriented tasks. Imagine how difficult it would be for a new user to figure
out that you have put your printing functionality under a menu called, for example, Technical Tasks -
> Hardware -> Printers -> Print.
Creating a Menu
1. Click the MenuEditor component at the bottom of the screen. This will allow you to start
entering menu items. Type in Fileand press Enter.
2. Click File, then underneath File where it displays text, as shown in Figure 1, type Open.
3. Repeat the steps to enter the Save, Recent, and Exit items to the File menu.
4. Add a menu item 'Edit' next to File and Add Cut, Copy, and Paste underneath it.
5. Add a Help menu with About, and Online items.
Now that you have the main menu sorted, let's take it a step further and add a submenu to the Open
menu item. To do this, follow these steps:
50
1. Click the Open menu item.
2. To the right of the Open menu item, you should see the 'Type Here' section.
3. Enter Text.
4. Underneath the Text menu item, enter Other (see Figure 2).
IAn Alt key shortcut enables you to press the Alt key and then the underlined letter to display the
menu. For example: If you press Alt + F, it should open the File menu. To make a letter in the menu
display underlined and act as an Alt key shortcut, follow these steps:
51
Shortcut keys are usually a combination of Ctrl and a letter. For example, Ctrl + C is the keyboard
shortcut for Copy and Ctrl + V is the Keyboard shortcut for Paste. To add a keyboard shortcut key to
a menu item, follow these steps:
Once you click on the button, the Select Resource box will appear. Here, you can select from already
added icons inside your project, or add new items to your project's resources (see Figure 5):
52
To Add a Separator bar to your menu, follow these steps:
1. Click the Menu Item that you want to separate from other menu items.
2. When the 'Type Here' text appears, look closely. There is a small drop-down arrow next to it,
as shown in Figure 2.
3. Select Separator from the displayed list.
Your finished Menus should look like those shown in Figures 6-8.
Opening Files
Add the following Namespace and code to make use of the OpenFileDialog to open a file. The code
is slightly different for the Text and Other file types (according to the menus):
1. Imports System.IO
2. Private Sub TextToolStripMenuItem_Click(sender As Object, _
3. e As EventArgs) Handles TextToolStripMenuItem.Click
4.
5. OpenFileDialog1.Filter = "*.txt|*.txt"
6.
7. If OpenFileDialog1.ShowDialog = DialogResult.OK Then
8.
9. OpenFile(OpenFileDialog1.FileName)
10.
53
11. End If
12.
13. End Sub
14.
15. Private Sub OpenFile(strFileName As String)
16.
17. Dim srStream As New StreamReader(strFileName)
18.
19. TextBox1.Text = srStream.ReadToEnd
20.
21. srStream.Close()
22.
23. End Sub
24.
25. Private Sub OtherToolStripMenuItem_Click(sender As Object, _
26. e As EventArgs) Handles OtherToolStripMenuItem.Click
27.
28. OpenFileDialog1.Filter = "*.*|*.*"
29.
30. If OpenFileDialog1.ShowDialog = DialogResult.OK Then
31.
32. OpenFile(OpenFileDialog1.FileName)
33.
34. End If
35.
36. End Sub
I set the Filters for the OpenFileDialog according to which option was selected, and then make use of
the Open sub to open the selected file.
Saving a File
Add the following code to save a file:
1. Private Sub SaveToolStripMenuItem_Click(sender As Object, _
2. e As EventArgs) Handles SaveToolStripMenuItem.Click
3.
4. SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
5.
6. If SaveFileDialog1.ShowDialog = _
7. Windows.Forms.DialogResult.OK Then
8.
9. My.Computer.FileSystem.WriteAllText _
10. (SaveFileDialog1.FileName, TextBox1.Text, True)
11.
12. End If
13.
14. End Sub
54
When the Save Menu item is clicked, a SaveFileDialog opens and writes the content of the Textbox
into a filename supplied by the user.
55
Positioning a control
MouseDown is the commonly used event and it is combined with the move method to move
an Image control to different locations in a Form. Open a new standard EXE project and save the
Form as Move.frm and save the project as Move.vbp Design the Form as shown below.
Name frmMouseDown
Name optCredit
Value True
Name optCash
Image Name imgCredit
Picture c:/credit.jpg
Image Name imgCash
Picture c:/cash.jpg
The follwoing code is entered in the general declarations section of the Form.
Option Explicit
Run the application by keying in F5. You can notice that when the mouse is clicked on the form
somewhere, the selected image moves to that clicked location. This is shown in the below figure.
56
Graphical Mouse Application In Visual Basic 6
The mouse events can be combined with graphics methods and any number of customized
drawing or paint applications can be created. The following application combines MouseMove and
MouseDown events, and illustrates a drawing program.
Open a new Standard EXE project and save the Form as Draw.frm and save the Project as
Draw.vbp. Name the caption of the as Drawing. Add command button control and name the caption
of it as Clear
Button value 1 indicates that the left mouse button is clicked. The code written in the MouseDown
event changes the CurrentX and CurrentY to the coordinates where the mouse button was just
clicked.
Run the application. You can notice that when the mouse is clicked and moved in the Form a line is
drawn corresponding to the mouse movement. Following figure illustrates the combined action of
MouseDown and MouseMove.
57
The program uses two graphics related Visual Basic concepts, the Line method and the
CurrentX and CurrentY properties. Line method is preferred to draw a line in a Form. The following
statement draws a line from the coordinates X = 2500, Y = 2000, X = 5000, Y = 5500
The CurrentX and CurrentY properties are not visible in the properties window of the Form
because it cannot be set at the design time. After using the Line method to draw a line in a Form,
Visual Basic automatically assigns the coordinate of the line's end point to the CurrentX and
CurrentY properties of the Form on which the line is drawn.
MouseMove application
Visual Basic does not generate a MouseMove event for every pixel the mouse moves over and
a limited number of mouse messages are generated per second by the operating environment. The
following application illustrates how often the Form_MouseMove ( ) event is executed.
Open a new standard EXE project and save the form as MouseMove.frm and save the Project
as MouseMOve.vbp. Place a CommandButton control and name the caption as Clear and set the
name as cmdClear.
The above procedure simply draws small circles at the mouse's current location using the
Circle method. The parameter x, y represent the centre of the circle, and the second parameter
represent the radius of the circle.
58
Dragging and Dropping:
A dialog box is simply a form in a program that contains input controls designed to receive
information. To make your programming faster, Visual Basic includes an ActiveX control, named
CommonDialog.
59
This table lists the name and purpose of the six standard dialog boxes that the common dialog object
provides and the methods you use to display them:
60
Creating a Color Dialog Box
If you need to update the color of a user interface element while your program runs, you can
prompt the user to pick a new color with the Color dialog box displayed by using the Common
Dialog object. The color selections provided by the Color dialog box are controlled by the Flags
property, and the Color dialog box is displayed with the ShowColor method.
The event procedure assumes that you have already created a menu command named
TextColor with the Menu Editor. See the code given below
EXERCISE: Creating a File Menu and Common Dialog Object Step by Step
In this exercise, you use the Menu Editor to create a File menu with Open, Close , and Exit
commands for your program. You also assign access keys and shortcut keys to the commands, so you
can run them from the keyboard.
1. Start Visual Basic and open a new, standard Visual Basic application.
2. On the toolbar, click Menu Editor to open the Menu Editor dialog box.
3. In the Caption text box, type &File.
4. In the Name text box, type mnuFile, and then click Next.
By placing the & character before the letter F, you specify F as the menu access key.
61
To assign access and shortcut keys
1. Verify that the CommonDialog control is in your project toolbox. If it isn't, add it now by using the
Project menu Components command.
2. To add a common dialog object to your form, double-click the CommonDialog control in the
toolbox, and then drag the object to the lower right-hand side of the form.
1. Click the Image control and create a large image object in the middle of your form. When you run
your program, the image object displays picture files with *.jpg extension on a form.
2. On the form, click Image1. To restore the Properties window to full size, double-click the
Properties window title bar.
If you cannot see the Properties window, click Properties on the toolbar to display it.
3. Click the Stretch property and set it to True.
When you run your program, Stretch makes the metafile fill the entire image object.
4. On the toolbar, click Save Project to save these changes to your program.
1. In the Project window, click View Code , click the Code window Object drop-down list box, and
then click mnuOpenItem.
2. In the mnuOpenItem_Click event procedure, type the following code:
62
Image1.Picture = LoadPicture(CommonDialog1.Filename)
mnuCloseItem.Enabled = True
3. In the Object drop-down list box, click mnuCloseItem, and then type the following code:
Image1.Picture = LoadPicture("")
mnuCloseItem.Enabled = False
4. In the Object drop-down list box, click mnuExitItem, and then type End in the event
procedure.
5. On the toolbar, click Save Project to save your changes.
To run the program
An MDI application must have at least two Form, the parent Form and one or more child
Forms. Each of these Forms has certain properties. There can be many child forms contained within
the parent Form, but there can be only one parent Form.
The parent Form may not contain any controls. While the parent Form is open in design
mode, the icons on the ToolBox are not displayed, but you can't place any controls on the Form. The
parent Form can, and usually has its own menu.
1. Start a new project and then choose Project >>> Add MDI Form to add the parent Form.
2. Set the Form's caption to MDI Window
3. Choose Project >>> Add Form to add a SDI Form.
4. Make this Form as child of MDI Form by setting the MDI Child property of the SDI Form to
True. Set the caption property to MDI Child window.
63
Visual Basic automatically associates this new Form with the parent Form. This child Form can't
exist outside the parent Form; in the words, it can only be opened within the parent Form.
The MDI Form usually has a menu with two commands to load a new child Form and to quit
the application. The child Form can have any number of commands in its menu, according to the
application. When the child Form is loaded, the child Form's menu replaces the original menu on the
MDI Form
Following example illustrates the above explanation.
* Open a new Project and name the Form as Menu.frm and save the Project as Menu.vbp
* Design a menu that has the following structure.
<> MDIMenu Menu caption
MDIOpen opens a new child Form
MDIExit terminates the application
* Then design the following menu for the child Form
<> ChildMenu Menu caption
At design time double click on MDI Open and add the following code in the click event of the open
menu.
Form1.Show
And so double click on MDI Exit and add the following code in the click event
End
Double click on Child Close and enter the following code in the click event
Unload Me
64
Before run the application in the project properties set MDI Form as the start-up Form. Save
and run the application. Following output will be displayed.
And as soon as you click MDI Open you can notice that the main menu of the MDI Form is
replaced with the Menu of the Child Form. The reason for this behavior should be obvious. The
operation available through the MDI Form are quite different from the operations of the child
window. M oreover, each child Form shouldn't have it's own menu.
Most of the other grid objects are specifically designed for data binding, whereas the
FlexGrid has many collections of properties, methods and events that lend themselves to
several environments in addition to just data-binding.
One of the most powerful applications of the FlexGrid is in managing data from
database tables in an unbound state. That is, to populate & edit the FlexGrid and write the
contents back to the database in code. This may seem a pointless exercise as objects such
Microsoft's Data Bound Grid Control are written specifically for this purpose, except these
grids simply display the contents of a recordset, record by record, field by field. Whereas the
FlexGid can populate the grid in any manner, examples of which are:
65
That said, most of the functionality found in these third party grids can be accessed
with FlexGrids .
To use the FlexGrid in your application, right click the Toolbox or select the Project menu and
choose 'Components'. The Components dialog box appears as shown in Figure 1.
Select Microsoft FlexGrid Control and copy the control onto your form from the Toolbox. The
default FlexGrid will appear on the form as shown in Figure 2.
66
There are a few simple formatting tips to improve to appearance of the FlexGrid:
First of all, it's good practice to determine the initial number of grid rows and columns
using the Row and Col properties respectively. Then set the number of fixed rows and
columns with the FixedRow and FixedCol properties respectively.
To ensure the columns are the correct width to fit inside to FlexGrid, first set a variable
to the width of the FlexGrid, allowing for a vertical Scrollbar width. Then use this
variable to resize to individual column widths, by dividing it by the number of
columns.
The height of individual rows can be changed to accommodate multi-line headings.
This is done by simply multiplying the appropriate row height by a scaling factor, in
this case two, to double the height.
When increasing the size of a row height, to make sure text uses the extra available
space, use the WordWrap property the ensure text continues on the the next cell line.
Regarding writing text to the grid there are two main methods. The first one is using
the Additem method, this writes text to an entire row in one action and is therefore
useful for adding headings. The vbTab constant is used to distinguish adjacent cells.
The second method to populate grid cells with text is to directly address individual
cells and using the TextMatrix or Text property and set the cell's text.
With MSFlexGrid
.ColWidth(0) = lngWidth / 4
.ColWidth(1) = lngWidth / 4
.ColWidth(2) = lngWidth / 4
.ColWidth(3) = lngWidth / 4
67
.TextMatrix(intLoopCount, 0) = "Item " & intLoopCount
Next intLoopCount
End With
The initialised FlexGrid should appear on the form as shown in Figure 3..
The ability to change the individual cell background colour and cell font colour is
useful for highlighting particular data states, e.g. values exceeding a specified ceiling, negative
values, cells where data cannot be entered etc.
To set the background colour of a cell, first reference the cell by setting the Row and
Col properties to the appropriate cell, then use the CellBackColor property to set its colour.
Similarly use the CellForeColor property to change the colour of the text displayed in a
cell. Examples of available colours are found in the FlexGrid's Properties Window under any
of the colour properties, especially the palette tab as this displays a wider range of colours.
To set a range of cells to a selected colour each cell must be referenced in turn, unless
all the cells in the grid are to have their colour set to the same colour in which case the
BackColor and ForeColor property can be used which sets the entire grid's colour.
68