Вы находитесь на странице: 1из 21

Visual Basic 5

Programming - 5
A Specialised Training Course
Contents
APPLICATION MENUS ..................................................................................................................................... 2
MENU DESIGN DIALOG BOX............................................................................................................................. 3
Caption Text Box...................................................................................................................................... 3
Name Text Box ......................................................................................................................................... 3
Index Text Box.......................................................................................................................................... 3
Shortcut Combo Box................................................................................................................................. 3
WindowList Check Box............................................................................................................................. 3
HelpContextID Text Box .......................................................................................................................... 3
Checked Check Box.................................................................................................................................. 3
Enabled Check Box .................................................................................................................................. 4
Visible Check Box..................................................................................................................................... 4
Layout Section .......................................................................................................................................... 4
PROPERTIES ...................................................................................................................................................... 4
EVENT PROCEDURES ........................................................................................................................................ 4
FILE I/O - DOCUMENTS ................................................................................................................................... 5
SEQUENTIAL FILES ........................................................................................................................................... 6
RANDOM-ACCESS FILES ................................................................................................................................... 7
BINARY FILES ................................................................................................................................................... 8
COMMON DIALOG BOX CONTROL............................................................................................................. 9
Action Property ........................................................................................................................................ 9
DialogTitle Property ................................................................................................................................ 9
Filename Property.................................................................................................................................... 9
DefaultExt Property ................................................................................................................................. 9
Filter / FilterIndex Properties ................................................................................................................ 10
Flags Property........................................................................................................................................ 10
InitDir Property...................................................................................................................................... 10
DRIVE, DIRECTORY AND FILE CONTROLS ............................................................................................ 10
DRIVE LIST BOX CONTROL............................................................................................................................. 11
Drive property ........................................................................................................................................ 11
DIRECTORY LIST BOX CONTROL .................................................................................................................... 11
Path Property ......................................................................................................................................... 12
FILE LIST BOX CONTROL ................................................................................................................................ 12
Filename Property.................................................................................................................................. 12
Path and Pattern Properties................................................................................................................... 12
Normal, Archive, Hidden, ReadOnly and System Properties................................................................. 12
MultiSelect Property............................................................................................................................... 13
COMBINING THE CONTROLS ........................................................................................................................... 13
APPENDIX.......................................................................................................................................................... 14
Common Dialog Flag Property Constants............................................................................................. 14
EXERCISES........................................................................................................................................................ 15

Visual Basic Book 5 © Mark Collins 1999 Page 1


Application Menus
To build considerable functionality into an application without needing screens full of
controls one needs to introduce a menu interface. By now you should be familiar with the
Windows menu standard. Most features can be built into your menus including...
1. Multi-level menus (to 5 levels)
2. Access Key definition (underlined character for use with Alt)
3. Short-cut key allocation (e.g. Ctrl-X)
4. Checked (toggle) menu options.
Each menu option is effectively a control with its own...
• Properties
• Click Event-procedure
• Adding a Menu to a Form
To add a menu to a form you should ensure that the relevant form is active and either...
Use the menu control button on the Toolbar
Select Tools / Menu Editor from the VB application window.
Use the short-cut key combination Ctrl-E
This brings up the Menu design dialog box. The following diagram shows one with some of
the menu structure already developed.

Visual Basic Book 5 © Mark Collins 1999 Page 2


Menu Design Dialog Box
The various controls appearing on this dialog box allow you to create, edit and delete
individual menu items and their properties. The bottom half allows you to design the whole
set of items. The top half allows you to set design-time properties for the selected menu item.

Caption Text Box


This determines what will appear in the menu as the caption. This is actually stored in the
Caption property of the individual menu control. You can specify the Access Key by
including an ampersand character before an instance of that character. To add a separator, use
a hyphen.

Name Text Box


As with any other control, your menu item requires a name stored in the Name Property. This
must be created in this text box; you can edit it later from here or with the Property window.
By giving individual menu items the same name you can create a control array just like any
other control type. You are limited to only including menu items at the same level.

Index Text Box


If you do create a control array of menu items they are not automatically given Index values
like other controls. Before you close the menu design dialog you must allocate an Index value
for each element yourself using this text box. This sets the Index property.

Shortcut Combo Box


This combo box (actually a drop down list box, see book 4 for definition) gives you the
possible key combinations you can allocate as shortcut keys. When allocating shortcut keys
you should consider conventions (Ctrl+X or Shift+Del for Cut etc...) and bear in mind any
possible conflicts. This is stored in the Shortcut property.

WindowList Check Box


If your application uses an MDI (Multiple Document Interface) then you may include a
section in your menu that lists any open documents to allow you to switch between them.
This Boolean value is stored in the WindowList property.

HelpContextID Text Box


We have not looked at creating help files yet, but when we do we will see how we can build
contextual links between controls and help topics.

Checked Check Box


This toggles the checked property between True and False. If True then a tick is displayed to
the left of the menu item. At runtime, clicking on the menu item does not automatically
toggle this on/off; that must be handled with code...
mnuFormatBold.Checked = Not
mnuFormatBold.Checked
If mnuFormatBold.Checked = True Then
...

Visual Basic Book 5 © Mark Collins 1999 Page 3


Enabled Check Box
This toggles the menu item’s Enabled Property between True (normal) and False (greyed and
inactive). This allows the developer to dynamically control the menu availability.

Visible Check Box


This toggles the menu item’s Visible Property between True (normal) and False (not
appearing). This also allows the developer to dynamically control the menu availability.

Layout Section
This part allows you to layout the menu adding, levelling and deleting items from the whole
menu bar. The top half of the dialog box, described above, always shows the current settings
of the selected item from this section.
It comprises of a set of buttons and a list box that displays a hierarchical list of menu items.
Submenu items are indented to indicate their hierarchical position or level. Use the left and
right arrow keys to change the level of a menu item from a higher level to a lower level. You
can create up to four levels of submenus. Use the up and down arrow keys to change the
position of a menu item within the same menu level (up or down in the menu list).
The Next button moves selection to the next line, Insert inserts a line in the list box before
the currently selected line while Delete deletes the currently selected line.

Properties
All of the important properties have been described above and can be changed using the
Menu Design Dialog Box. Once the items have been created you can view the properties for
any menu item by using the drop list box at the top of the property window. Most can also be
changed at runtime.

Event Procedures
Each bottom level menu item can have a click_procedure defined for it. This can be quickly
accessed by ‘selecting’ the menu item at design time.

Visual Basic Book 5 © Mark Collins 1999 Page 4


File I/O - Documents
Most applications need some way of storing data between sessions. For database applications
we can use specialist controls to use MS-Access files. You can save your word-processing
document in a file that may contain more than just text. Whatever we do we need file formats
to store data. Your application may not necessarily be able to make use of an existing format
so you may need to create your own. Before we investigate this further we need to establish
some basics.
There are three data file types supported in Visual Basic without resorting to Custom
Controls...
• Sequential Files
• Random-Access Files
• Binary Files
They each have their advantages, disadvantages and uses. Sequential files are the easiest to
understand and program but they are not particularly flexible and can incur performance
drawbacks. Handling random-access files is a bit more involved but they are often quicker at
performing I/O operations. They are also quite rigidly structured. Binaries offer the greatest
flexibility but because of their lack of internal structure, they are the most programming
complexity.
Each type of file needs to be opened, closed and often amended. Each open file is identified
by a file number associated with it, when opened. This file number should always be used in
each I/O call, it is possible to use Constants.
NB. We cannot be sure of what file numbers are already allocated, therefore it is best to let
the computer provide the next available number; this is easily done by using the FreeFile
command, i.e. filenumber = FreeFile, which allocates the next available unused file handle
number to the variable called filenumber. While the file formats are quite different in nature,
they all use the same Open and Close statements:
Open ‘pathname’ For ‘mode’ [Access access] As [#] filenumber
pathname - specifies path and name of the file to open.
mode - specifies the file mode: Append, Binary, Input, Output, or
Random (default).
Access - specifies the operations permitted on the open file: Read, Write, or
Read Write. It is optional.
Close [filenumber]
if the filenumber is omitted then it all active files opened by the Open
statement are closed.
Examples:
i) Open "TESTFILE" For Binary Access Write As #1
ii) Open "TESTFILE" For Input As #1
iii) Close #3

Visual Basic Book 5 © Mark Collins 1999 Page 5


Sequential Files
Effectively these are text files where each character can be read sequentially and represents
either a text character or text formatting character (such as Tab). It is relatively simple to
develop procedures to read and write sequential files using the following statements...

Function/ Description
Statement
Input$ Reads in a fixed number of characters from the file. If no. of characters is not
specified, it reads a whole file up to 65,535 characters long.
Input# Allows you to read data from a sequential file and place the values read into a
sequence of variables.
Line Input# Used to read data in a line at a time (i.e. until a Carriage return)
Write# / Used to write data from a list of expressions, in either comma-delimited (Write)
or space delimited format.
Print#
Several points must be remembered...
• To change between Input, Output and Append modes the file must be closed and
re-opened in the new mode.
• A file must exist before it is opened for Input or Append. Output mode creates a
new file or overwrites an old file.
• Although it is usual to read and write sequential files sequentially it is possible to
move the file pointer about using Seek
So, basically, you use Input when you want to read from the file, Output when you want to
write or overwrite part of the file and Append when you want to add to the file.
Example
This piece of code opens a file, the path and name of which is stored in the FileName string
variable. The text is read into a single text box.
...
Open FileName For Input As 1
If LOF(1) > 30000 Then
Msg = “The file is too large”
MsgBox Msg, 16, “File too Big”
Else
txtMainText.Text = Input$(LOF(1), 1)
End If
Close 1
...

( Note: The statement LOF means ‘ length of file’ )


Later in the application we can save the amended text back into the same file.
...
Open FileName For Output As 1
Print #1,txtMainText.Text
Close 1
...

Visual Basic Book 5 © Mark Collins 1999 Page 6


To append a sequence of data to a different file we would use...
...
Open FileName For Append As 3
...
Write #3, EmpName$, Salary&, Age%
...
Close 3
...

If we are going to do record type work in sequential files it is worth using user-defined
data- types for brevity and accuracy.

Random-Access Files
This file type (otherwise known as simply Random) is generally used to store a series of
identical length records. Each record must be of a single data-type, but as we know we can
always create our own user-defined types. Technically you need to know the length of your
data types, but it is easier to use a function that works that out for you ‘LEN’. This
information is required when you open the file.
The main feature of this file access method is that you can read and write records wherever
they are in the file in a non-sequential manner; you can also mix reading and writing without
needing to change the mode of access.
The main statements we will use are...
Function/ Description
Statement
Open Allows you to open a Random file.
Open file for Random As filenumber Len=recordlength.
Close Closes an open file.
Get This copies a record from a specific position in the given file to the given
variable. e.g.
get filenumber, Position, Variable

Put This (over)writes a record to a specific position in the given file from a given
variable. e.g.
put filenumber, Position, Variable

Several points need to be considered...


• To add a new record you need to Put it in the position one more than the current
number of records.
• To delete a record in the middle of the file you need to shift the subsequent
records up one place. The last record should be overwritten with a blank record
and taken care of later.
• All strings (even within user defined types) must be of fixed lengths.

Visual Basic Book 5 © Mark Collins 1999 Page 7


• The files are not easily interchangeable with other applications.
Example
Firstly a record type needs to be defined.
Type Employee
Name As String
Age As Integer
Salary As Currency
End Type
...
Then we must open a file…
...
Open FileName For Random As 2 Len =
Len(Employee)
...
Then assuming we have a variable of type employee called Person and an Integer variable
storing our Position we can read from the file to it...
Get 2, Position, Person
The values contained in Person can be presented and amended in several controls and written
back to the file by...
Put 1, Position, Person

Binary Files
The possibilities are endless, you can store the data in the manner you want. The only
problem is to make sure that you always read and write in a consistent manner as the
restrictions of the other types aren’t around to control matters.
If you do store record type information within binary files you have both the advantage and
disadvantage of variable length records. Variable length records can save space, but they
require a lot more ‘handling’.
You use Get and Put similar to Random files, but you can get and put any length variable at
any position.
Where this becomes useful is in applications where you need ‘header’ information contained
before other data. The other data can be text, bitmap graphic information, sound or anything.
The best way to keep track of this is to define a user defined data-type for your header
information which is always placed at the start of the file. This can be read in using one Get
statement, the rest of the data can then be read using a loop until the end of file is reached.
If you are using data files then you need some procedures for your user to open and save
them, but there are controls to help you select the file names, directories and drives.

Visual Basic Book 5 © Mark Collins 1999 Page 8


Common Dialog Box Control
The simplest way to select a file either to open or save is to use the Common Dialog Box
Control. This provides a standard set of dialog boxes for operations such as opening, saving,
and printing files or selecting colours and fonts.
You create common dialog boxes for your application by adding the common dialog control
to a form and setting its properties. The controls do not do the opening and saving, but they
do allow you to select valid paths and filenames.
At design time, the common dialog control appears as an icon on a form. This icon can not be
resized and does not appear at runtime. The control has several important properties.

Action Property
The type of dialog box displayed is determined by the Action property. The values of the
Action property and therefore the types of dialog boxes are...
Action Dialog Type
0 No Action
1 Open
2 Save As
3 Color (sic)
4 Font
5 Print
6 Invoke WINHELP.EXE
To display a Common Dialog Box at runtime you set the Action property to the type of
Dialog required. Other properties such as file name filters should be set before setting this
property.

DialogTitle Property
This determines the Title Bar text of the Dialog Box.
For now we will concentrate on properties relevant to file operations.

Filename Property
This is the property that actually captures the filename and path generated by the Open and
Save As boxes. This is then passed to the procedure that actually opens/saves the file.

DefaultExt Property
When using the Save As Dialog Box this defines the default file extension that is added to the
filename unless otherwise specified.

Visual Basic Book 5 © Mark Collins 1999 Page 9


Filter / FilterIndex Properties
Available as an alternative / complement to the DefaultExt property and is used in both Open
and Save As dialogs. The Filter property allows you to define several file filters that
determine which files are shown in the file list. The property actually contains a string with
the following syntax...
“Filter Name | Pattern [Filter Name |
Pattern ...]”
for example...
“All files | *.* | Text Files | *.TXT |
INI files | *.INI”
used as the filter for an Open dialog box would result in the All files filter being used, but the
“List Files of type” drop list will contain two alternatives.
The FilterIndex specifies which filter to use, the default and lowest value is 1 (one, why not
zero?) but you can specify any value up to the number of filters.

Flags Property
This property allows you to combine several constants as a single value to define various
options for the Open and Save As dialog boxes. The flag constants represent various bit
patterns that can be combined using the Or operator in a bit-wise context. See the table in the
Appendix for the full set.
An example of their use would be...
CMDialog1.Flags = OFN_SHOWHELP Or
OFN_HIDEREADONLY
or
CMDialog1.Flags = &H14& ‘ &H10& Or &H4&
which displays a help button in the associated dialog and hides the Read Only check box.

InitDir Property
Determines the drive and directory to default to.

Drive, Directory and File Controls


There will be times when the versatile Common Dialog Box Control is not suitable for some
file operations. This may be when you need to...
• use a bespoke Open and Save As Dialog Box
• perform other file operations (delete, rename, list etc.)
• perform directory specific operations (cd, md, rd etc)
• perform drive specific operations (e.g. select drive to analyse)
To do this there are separate controls for each level, namely...
• Drive List Box Control
• Directory List Box Control
• File List Box Control

Visual Basic Book 5 © Mark Collins 1999 Page 10


These usually need to be combined, but may appear in various combinations.

Drive List Box Control


This is simply a drop-down list box containing the names and volume labels of all available
disk drives on your system. Icons are included beside each entry to indicate the type of drive.

As for its properties, it has List, ListIndex and ListCount properties that can be used like any
other list. It does have a vital property however...

Drive property
The property that actually stores the pertinent data this is a string property that specifies the
selected drive. It is only available at run-time.
By selecting a drive from the list the drive property contains the drive letter. Alternatively you
can set the drive by assigning it a string. Note that it only takes the first character, which is
useful in that we can assign a whole path string from which it picks the relevant information.
ChDrive drvSelectDrive.Drive ‘ Set
Current Drive to selection
drvSelectDrive.Drive = CurDir$ ‘Set
Control Drive to Current drive

Directory List Box Control


We can’t compare this with a list control we have seen already, the closest comparison can be
made with the custom Outline Control, a special type of list box that allows you to display
items in a list hierarchically.

The directory structure is represented graphically as well as textually; a small folder is placed
to the left of the directory name, and they are indented to show the parent~subdirectory
relationships. The directories can be browsed through by using the mouse to move up and
down the directory tree.

Visual Basic Book 5 © Mark Collins 1999 Page 11


Path Property
This property determines the current absolute path, including the drive name and like the
Drive Control’s Drive property is not available at design time.
The value of the Path property is a string indicating a path, such as “C:\VB”. The default is
the current path when the control is created at run time. Changing the value of the Path
property generates a Change event.
Examples of its use are...
dirSelectDir.Path = “F:\BIN\DATA”
drvSelectDrive.Drive = dirSelectDir.Path
The second example shows how we can link the drive and directory controls one way. How
about changing the path when we change a drive?
dirSelectDir.Path = drvSelectDrive.Drive
Our reversed assignment works too, the Path property in the directory control becomes the
current directory for the selected drive letter (not necessarily the root).

File List Box Control


To complete our trio we need to be able to select individual files. The File List Box is just
that, a list box, to allow editing of filenames you need to attach a text box too.
As this is the detail end of the combination of controls there are several properties to
consider.

Filename Property
This is the important data property of the control. It contains not only a filename, but also the
full drive and directory path. This property can not be set at design time.

Path and Pattern Properties


The combination of the two properties, determine which files appear in the list. The Path
property is virtually identical to the Directory List Box property of the same name and
contains the same level of detail. In this context it identifies the current directory from which
to display files.
The Pattern property then filters out the file names to appear based upon their names. The
default is *.* but any wildcard combination is possible.

Normal, Archive, Hidden, ReadOnly and System Properties


Works in conjunction with the above properties to determine which files appear in the list
based upon their attributes. Normal represents a combination of the attributes, i.e. Archive set
but the others off.
Each property can have a True/False value. If the property is True then files with the related
attribute set will be included.
The defaults are: True for Normal and Archive, but False for the rest.
In use you could have a group of check boxes, one for each attribute, and link their value to
the equivalent property.

Visual Basic Book 5 © Mark Collins 1999 Page 12


MultiSelect Property
In situations where you need to perform tasks related to several files (move, delete, print etc.)
it is possible to set the MultiSelect to 1 or 2. This behaves the same as an ordinary list box
and you should refer to the section on list boxes earlier in the course for more information.

Combining the Controls


The three levels of controls are independent objects on your form. You need to write the code
to link them. If you need to edit the filename (a Save As situation for example) you can link
in a text box too.
Basically when one of the controls changes you need to have processing in place to change
the others if necessary. The system helps in that when you change the path in the directory list
the change event-procedure is automatically activated, so we can link them as follows...
A change of Drive changes path of Directory to a new drive ...
Sub drvX_Change()
dirX.Path = drvX.Drive
...
End Sub
Automatically changes the appearance of the directory list and activates ...
Sub dirX_Change()
filX.Path = dirX.Path
...
End Sub
Which in turn updates the file list.

The possibility exists that using a text box or whatever we change the filename property of
the File list, including new drive and directory information. This automatically changes the
Path property of the File list. In this case we need to possibly update the other controls...
Sub filX_Change()
dirX.Path = filX.Path
drvX.Drive = filX.Path ‘takes first
letter
...
End Sub

Visual Basic Book 5 © Mark Collins 1999 Page 13


Appendix
Common Dialog Flag Property Constants
Constant Value Description
cdlOFNAllowMultiselect &H200 Specifies that the File Name list box allows multiple
selections. The user can select more than one file at run time
by pressing the Shift key and using the Up and Down Arrow
keys to select the desired files. When this is done, the
FileName property returns a string containing the names of
all selected files. The names in the string are delimited by
spaces.
cdlOFNCreatePrompt &H2000 Specifies that the dialog box should ask if the user wants to
create a file that does not currently exist. This flag
automatically sets the cdlOFNPathMustExist and
cdlOFNFileMustExist flags.
cdlOFNExtensionDifferent &H400 Indicates that the extension of the returned file name is
different from the extension specified by the DefaultExt
property. This flag is not set if the DefaultExt property is
Null, if the extensions match, or if the file has no extension.
This flag value can be checked upon returning from the
dialog box.
cdlOFNFileMustExist &H1000 Specifies that the user can enter only names of existing files
in the File Name text box. If this flag is set and the user enters
an invalid file name, a warning is displayed. This flag
automatically sets the cdlOFNPathMustExist flag.
cdlOFNHideReadOnly &H4 Hides the Read Only check box.
cdlOFNNoChangeDir &H8 Forces the dialog box to set the current directory to what it
was when the dialog box was invoked.
cdlOFNNoReadOnlyReturn &H8000 Specifies that the returned file will not have the Read Only
attribute set and will not be in a write-protected directory.
cdlOFNNoValidate &H100 Specifies that the common dialog box allows invalid
characters in the returned file name.
cdlOFNOverwritePrompt &H2 Causes the Save As dialog box to generate a message box if
the selected file already exists. The user must confirm
whether to overwrite the file.
cdlOFNPathMustExist &H800 Specifies that the user can enter only valid path names. If this
flag is set and the user enters an invalid path name, a warning
message is displayed.
cdlOFNReadOnly &H1 Causes the Read Only check box to be initially checked when
the dialog box is created. This flag also indicates the state of
the Read Only check box when the dialog box is closed.
cdlOFNShareAware &H4000 Specifies that sharing violation errors will be ignored.
cdlOFNHelpButton &H10 Causes the dialog box to display the Help button.

Visual Basic Book 5 © Mark Collins 1999 Page 14


Exercises
Exercise 1
The object of this exercise is to familiarise yourself with various aspects of file Input
and Output. It is a VERY simple text editor but it also incorporates some simple
error handling which is very important when manipulating data files.
1 Start a new project called InpOut.vbp and InpOut.frm. Also make sure that there is a
‘temp’ directory on your C: drive.
2 Set up a form with four command buttons and a text box and set their properties as
below:

Type Name Caption


Command Button cmdRead Read
Command Button cmdWrite Write
Command Button cmdDelete Delete
Command Button cmdCreate Create

3 In the code below you will notice a few extra statements that you haven’t yet come
across:
Dir - similar to the DOS command of the same name, it returns a string based on the
search criteria passed to it
Kill - deletes the file specified
LOF - ‘length of file’ returns the size of the file

4 Type in the following:

Option Explicit

Private Sub cmdCreate_Click()


Open "C:\temp\test.seq" For Output As 1
Print #1, txtMainText.Text
Close 1
End Sub

Visual Basic Book 5 © Mark Collins 1999 Page 15


Private Sub cmdDelete_Click()
If FileCheck = True Then
Kill ("c:\temp\test.seq")
End If
txtMainText.Text = ""
End Sub

Private Sub cmdRead_Click()


Dim msg As String
Dim disp As String
If FileCheck = True Then
Open "C:\temp\test.seq" For Input As 1
If LOF(1) > 30000 Then
msg = "The file is too large"
MsgBox msg, 16, "File too Big"
Else
Input #1, disp
txtMainText.Text = disp
End If
Close 1
End If
End Sub

Private Sub cmdWrite_Click()


If FileCheck = True Then
Open "C:\temp\test.seq" For Output As #1
Write #1, txtMainText.Text
Close 1
End If
txtMainText.Text = ""
End Sub

Visual Basic Book 5 © Mark Collins 1999 Page 16


Private Function FileCheck()
Dim value As Boolean
Dim msg As String
value = True
If Dir("C:\temp\test.seq") = "" Then
msg = "File cannot be found"
MsgBox msg, vbExclamation, "Error"
value = False
End If
FileCheck = value
End Function

Why do you think that error checking is particularly important when dealing data files?
Add extra features to enable only the appropriate buttons when file exists/ not exists, etc.

Visual Basic Book 5 © Mark Collins 1999 Page 17


Exercise 2
In this exercise we will create another simple text editor using a single text box. We
will read and write text files to and from disk but this time using Menus and Common
Dialog Boxes.
1 Start a new project called TEXTEDIT.VBP
2 Include the Common Dialog Control in your toolbox (Click Projects/Components )
3 Place a single text box in your form. Do not worry about it’s size, that will be dealt
with using code. Also place a Common Dialog Control on your form. Use the
following properties...
Type Name Caption / Text Other...
Form frmTextEdit My Editor
Text Box txtMainText blank MultiLine = True
Common Dlg CMDialog1 n/a not worth
changing

4 Firstly the code that will set the text box to the same size as the form. We need to
activate this when we Load the Form and if we resize it. Place it in Form_Resize and
call it from Form_Load.

Sub Form_Resize ()
txtMainText.Left = 0
txtMainText.Top = 0
txtMainText.Width = frmTextEdit.Width
txtMainText.Height = frmTextEdit.Height
End Sub

Sub Form_Load ()
Form_Resize
End Sub

Also set up a single declared variable in General / declarations


Dim Filename As String
5 Next we need controls to open and save our text, not forgetting exiting. Time to add a
menu.
• Activate Menu Design Box by right-mouse clicking on the form
• Create a new entry with the caption &File, call it mnuFile
• Click Next followed by the right arrow button. Give this new submenu the
caption &Open... and the name mnuFileOpen
• Click Next once more, give its entry caption Save &As... and the name
mnuFileSave
• Click Next again, place a single hyphen in the Caption and give it the name
mnuSep
Visual Basic Book 5 © Mark Collins 1999 Page 18
• Click Next once more and create an entry with caption &Quit, name
mnuFileQuit. Also select Ctrl+Q as the shortcut key
6 Now, to attach code to these menu items. Close the Menu Design Box and look at
your form. Note that a menu has appeared. To call up the code window for each menu
item just select it here at design-time.
Sub mnuFileOpen_Click ()
'Set up Open CMD
CMDialog1.DialogTitle = "Open..."
CMDialog1.Filter = "All
Files|*.*|Text Files|*.TXT|INI 
Files|*.INI"
'Invoke open CMD
CMDialog1.Action = 1
'Use selected filename
Filename$ = CMDialog1.Filename
If Filename <> "" Then
Open Filename For Input As 1
If LOF(1) > 30000 Then
Msg = "The file is too
large"
MsgBox Msg, 16, "File too
Big"
Else
txtMainText.Text =
Input$(LOF(1), 1)
End If
End If
Close 1
End Sub

Sub mnuFileSave_Click ()
CMDialog1.DialogTitle = "Save
As..."
CMDialog1.Action = 2
Filename$ = CMDialog1.Filename
Open Filename For Output As 1
Print #1, txtMainText.Text
Close 1
End Sub

Sub mnuFileQuit_Click ()
End
End Sub

7 Save your files as TEXTEDIT.FRM then try out your new editor.
Note that, just by using the common dialog control we have made the program a lot
more intuitive to the user and reduced the amount of code we have to type (which is
always a good thing...)
8 Your turn. Develop your editor so that...
• A second menu heading captioned &Text is added with sub-menus &Bold and
&Italic. Try attaching sensible shortcut keys to these. Their code simply switches
bold and italic on and off in the text box. Make sure a check (tick) appears beside
the menu item when switched on.
Visual Basic Book 5 © Mark Collins 1999 Page 19
• How about inserting an Edit section after the File section. Build in some simple
cut, copy and paste using the text box Sel*** properties.
• Disable the Save As menu option if the text box is empty.
• Add extra code in the QueryUnload of the frmTextEdit to enable the user to save
any changes before exiting from the text editor.

Visual Basic Book 5 © Mark Collins 1999 Page 20

Вам также может понравиться