0% found this document useful (0 votes)
27 views

Unit 2

Uploaded by

Rajashree B
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Unit 2

Uploaded by

Rajashree B
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT-II

Menus ,Mouse Events and dialog Boxes:


Introduction:
Menu Interface:

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 Editor window.

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.

Figure 1: Type Here

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

Figure 2: Example Menu items

Adding Alt Key Shortcuts

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:

1. Click the desired Menu item.


2. Open the Properties Window.
3. Add an ampersand in front of the desired letter to be used as a shortcut. In Figure 3, I have
added an ampersand in front of the O in Open.

Figure 3: Alt key shortcut added to Open menu

Adding Keyboard Shortcut Keys to Menus

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:

1. Click the desired Menu Item.


2. Open the Properties Window.
3. Find the Shortcut keys Property.
4. Set the desired Shortcut, as displayed in Figure 4.

Figure 4: Adding Shortcut keys to the Cut Menu item

The Shortcut will be displayed next to the Menu item's text.

Adding Icons to Menu Items


To add a small icon next to the Menu Item, follow these easy steps:
1. Click the desired menu item.
2. Open the Properties Window.
3. Select the Icon Property.

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

Figure 5: Selecting an Icon for a Menu Item

Adding a Separator Bar inside the Menu

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.

Figure 6: File Menu

Figure 7: Edit Menu

Figure 8: Help Menu

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.

Cut, Copy, and Paste


Add the following code to be able to Cut, Copy, and Paste text:
1. Private Sub CopyToolStripMenuItem_Click(sender As Object, _
2. e As EventArgs) Handles CopyToolStripMenuItem.Click
3.
4. Clipboard.SetText(TextBox1.SelectedText)
5.
6. End Sub
7.
8. Private Sub CutToolStripMenuItem_Click(sender As Object, _
9. e As EventArgs) Handles CutToolStripMenuItem.Click
10.
11. Clipboard.SetText(TextBox1.SelectedText)
12. TextBox1.SelectedText = ""
13.
14. End Sub
15.
16. Private Sub PasteToolStripMenuItem_Click(sender As Object, _
17. e As EventArgs) Handles PasteToolStripMenuItem.Click
18.
19. TextBox1.SelectedText = Clipboard.GetText
20.
21. End Sub

Mouse Events In Visual Basic 6


 Visual Basic responds to various mouse events, which are recognized by most of the controls. The
main events are MouseDown, MouseUp and MouseMove. MouseDown occurs when the user
presses any mouse button and MouseUp occurs when the user releases any mouse button.
 These events use the arguments button, Shift, X, Y and they contain information about the mouse's
condition when the button is clicked.
 The first argument is an integer called Button. The value of the argument indicates whether the left,
right or middle mouse button was clicked.
 The second argument in an integer called shift. The value of this argumnet indicates whether the
mouse button was clicked simultaneously with the Shift key, Ctrl key or Alt key.
 The third and fourth arguments X and Y are the coordinates of the mouse location at the time the
mouse button was clicked. As the Form_MouseDown( ) is executed automatically whenever the
mouse button is clicked inside the Form's area the X, Y co-ordinates are referenced to the form.

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.

Object Property Setting

Form Caption MouseDown

Name frmMouseDown

OptionButton Caption Credit card is selected

Name optCredit

Value True

OptionButton Caption Cash is selected

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

The following code is entered in the Form_MouseDown( ) event

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


If optCredit = True Then
imgCredit.Move X, Y
Else
imgCash.Move X, Y
End If
End Sub

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

Enter the following code in the Form_MouseDown ( ) procedure, Form_MouseMove ( )


procedure and cmdClear_Click ( ) procedures respectively.

Private Sub cmdClear_Click()


frmDraw.Cls
End Sub

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


frmDraw.CurrentX = X
frmDraw.CurrentY = Y
End Sub

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


If Button = 1 Then
Line (frmDraw.CurrentX, frmDraw.CurrentY)-(X, Y)
End If
End Sub

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

Line (2500, 2000) - (5000, 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 following code is entered in the cmdClear_Click ( ) and Form_MouseMove ( ) events


respectively.

Private Sub cmdClear_Click()


frmMouseMove.Cls
End Sub

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


Circle (X, Y), 70
End Sub

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:

Creating Dialog Boxes

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.

Using the Common Dialog Control


To add the CommonDialog control to the toolbox
1. From the Project menu, click Components.
2. Click the Controls tab.
3. Ensure that the Selected Items Only box is not checked.
4. Place a check mark next to Microsoft Common Dialog Control, and then click OK.
To create a common dialog object on your form
1. In the toolbox, double-click the CommonDialog control.
2. When the common dialog object appears on your form, drag it to an out -of-the-way location.

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:

Common Dialog Object event Procedures

The following topics are included in this section:

 Creating an Open Dialog Box


 Creating a Color Dialog Box

Creating an Open Dialog Box


The following code window shows an event procedure named mnuOpenItem_Click. You can
use this event procedure to display an Open dialog box when the user clicks the Open command on
the File menu. The event procedure assumes that you have already created a File menu containing
Open and Close commands and that you want to open Windows metafiles (.wmf).
Private Sub mnuOpenItem_Click()
CommonDialog1.Filter = "Metafiles (*.WMF)|*.WMF"
CommonDialog1.ShowOpen
Image1.Picture = LoadPicture(CommonDialog1.FileName)
mnuCloseItem.Enabled = True
End Sub

The event procedure uses these properties and methods:

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

Private Sub mnuTextColorItem_Click()


CommonDialog1.Flags = &H1&
CommonDialog1.ShowColor
Label1.ForeColor = CommonDialog1.Color
End Sub

The figure below shows the color dialog box.

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.

To create a File menu

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. In the Caption text box, type &Open….


2. In the Name text box, type mnuOpenItem.
3. To indent the selected (highlighted) command, click the right arrow button.
4. In the Shortcut drop-down list, click CTRL+O for a shortcut key, and then click Next.
5. In the Caption text box, type &Close.
6. In the Name text box, type mnuCloseItem.
7. In the Shortcut drop-down list, click CTRL+C for a shortcut key, and then click Next.
8. In the Caption text box, type E&xit.
9. In the Name text box, type mnuExitItem.
10. In the Shortcut drop-down list, click CTRL+X for a shortcut key, and then click OK.

To save your project

1. From the File menu, click Save Project As.


2. Save your form and project to disk under the name “Picture”. Visual Basic will prompt you for two
file names — one for your form file (Picture.frm), and one for your project file (Picture.vbp).

To create a common dialog object

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.

To create the image object

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.

To write event procedures

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:

CommonDialog1.Filter = "JPEG FILES (*.JPG)|*.JPG"


CommonDialog1.ShowOpen

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

1. On the Visual Basic toolbar, click Start.


Visual Basic loads the program and the form with its File menu.
2. From the File menu, click Open.
3. When the Open dialog box appears, load a picture file from your computer.
The picture selected should appear correctly sized in your image object.
4. From the File menu, click Close.
Your program should clear the picture file and turn off the Close command.
5. Try using the access keys and the shortcut keys to run the File menu commands. When you’re
finished, click the File menu Exit command.

The Multiple Document Interface (MDI) in Visual Basic 6


The Multiple Document Interface (MDI) was designed to simplify the exchange of
information among documents, all under the same roof. With the main application, you can maintain
multiple open windows, but not multiple copies of the application. Data exchange is easier when you
can view and compare many documents simultaneously.

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.

To create an MDI application, follow these steps:

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.

Parent and Child Menus

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

 Child Open opens a new child Form


 Child Save saves the document in the active child Form
 Child Close Closes the active child Form

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.

Using the FlexGrid control

Using Microsoft's FlexGrid control (MSFLXGRD.OCX) you can create utilities to


display, filter, edit, validate and update your data. For example, such utilities could include:
1. data entry & validation
2. high level reports
3. ported spreadsheet macro applications retaining cell layout & format

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:

1. separating grouped data with blank rows/columns,


2. adding sub/grand-total rows/columns,
3. changing the colour of the cell background or text in individual or multiple cells,
4. reacting to the state of the data, e.g. highlighting negative values,
5. validating entered data e.g., numeric values, positive values, permitted date ranges etc.

65
That said, most of the functionality found in these third party grids can be accessed
with FlexGrids .

Using the FlexGrid

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.

Figure : Components Dialog Box

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.

Figure : Default FlexGrid Appearance

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.

An example of grid initialisation code would be as follows:

Dim lngWidth As Long


Dim intLoopCount As Integer
Const SCROLL_BAR_WIDTH = 320

With MSFlexGrid

lngWidth = .Width - SCROLL_BAR_WIDTH


.Cols = 4
.FixedCols = 1
.Rows = 0
.AddItem vbTab & "Heading Text One" & vbTab & _
"Heading Text Two" & vbTab & "Heading Text Three" & _
vbTab & "Heading Text Four"
.Rows = 12
.FixedRows = 1
.WordWrap = True
.RowHeight(0) = .RowHeight(0) * 2

.ColWidth(0) = lngWidth / 4
.ColWidth(1) = lngWidth / 4
.ColWidth(2) = lngWidth / 4
.ColWidth(3) = lngWidth / 4

For intLoopCount = 1 To (.Rows - 1)

67
.TextMatrix(intLoopCount, 0) = "Item " & intLoopCount
Next intLoopCount
End With

The initialised FlexGrid should appear on the form as shown in Figure 3..

Figure : Initialised FlexGrid Appearance

Changing Cell Background & Foreground Colours

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

You might also like