visual basic 5-6 course part 5
Post on 30-May-2018
221 Views
Preview:
TRANSCRIPT
-
8/9/2019 Visual Basic 5-6 Course Part 5
1/21
Visual Basic 5Programming - 5A Specialised Training Course
-
8/9/2019 Visual Basic 5-6 Course Part 5
2/21
Visual Basic Book 5 Mark Collins 1999 Page 1
Contents
APPLICATION MENUS......................................................... ........................................................... ................. 2
MENU DESIGN DIALOG BOX........................................................... ........................................................... ....... 3Caption 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 ..................................................... ........................................................... ........................... 6RANDOM-ACCESS FILES....................................................... ........................................................... ................. 7BINARY 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.................................................... ........................................................... ..... 11Path 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
-
8/9/2019 Visual Basic 5-6 Course Part 5
3/21
Visual Basic Book 5 Mark Collins 1999 Page 2
Application MenusTo build considerable functionality into an application without needing screens full ofcontrols 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 ofthe menu structure already developed.
-
8/9/2019 Visual Basic 5-6 Course Part 5
4/21
Visual Basic Book 5 Mark Collins 1999 Page 3
Menu Design Dialog Box
The various controls appearing on this dialog box allow you to create, edit and deleteindividual menu items and their properties. The bottom half allows you to design the wholeset 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 theAccess Key byincluding an ampersand character before an instance of that character. To add a separator, usea hyphen.
Name Text Box
As with any other control, your menu item requires a name stored in theName Property. Thismust 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 acontrol array just like anyother 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 valueslike 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 theIndex property.
Shortcut Combo Box
This combo box (actually a drop down list box, see book 4 for definition) gives you thepossible key combinations you can allocate as shortcut keys. When allocating shortcut keysyou should consider conventions (Ctrl+X or Shift+Del for Cut etc...) and bear in mind anypossible 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 BoxWe have not looked at creating help files yet, but when we do we will see how we can buildcontextual links between controls and help topics.
Checked Check Box
This toggles thechecked property between True and False. If True then a tick is displayed tothe 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 =NotmnuFormatBold.Checked
If mnuFormatBold.Checked = TrueThen...
-
8/9/2019 Visual Basic 5-6 Course Part 5
5/21
Visual Basic Book 5 Mark Collins 1999 Page 4
Enabled Check Box
This toggles the menu itemsEnabled Property between True (normal) and False (greyed and
inactive). This allows the developer to dynamically control the menu availability.
Visible Check BoxThis toggles the menu items Visible Property between True (normal) and False (notappearing). 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 wholemenu bar. The top half of the dialog box, described above, always shows the current settingsof 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 andright arrow keys to change the level of a menu item from a higher level to a lower level. Youcan 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 bechanged at runtime.
Event Procedures
Each bottom levelmenu item can have a click_procedure defined for it. This can be quicklyaccessed by selecting the menu item at design time.
-
8/9/2019 Visual Basic 5-6 Course Part 5
6/21
Visual Basic Book 5 Mark Collins 1999 Page 5
File I/O - DocumentsMost applications need some way of storing data between sessions. For database applicationswe 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 formatsto store data. Your application may not necessarily be able to make use of an existing formatso 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 performancedrawbacks. Handling random-access files is a bit more involved but they are often quicker atperforming 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 programmingcomplexity.
Each type of file needs to be opened, closed and often amended. Each open file is identifiedby afile number associated with it, when opened. This file number should always be used ineach 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 letthe 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 handlenumber 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, orRead 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
-
8/9/2019 Visual Basic 5-6 Course Part 5
7/21
Visual Basic Book 5 Mark Collins 1999 Page 6
Sequential Files
Effectively these are text files where each character can be read sequentially and representseither a text character or text formatting character (such as Tab). It is relatively simple todevelop procedures to read and write sequential files using the following statements...
Function/
Statement
Description
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 asequence of variables.
Line Input# Used to read data in a line at a time (i.e. until a Carriage return)
Write# /
Print#
Used to write data from a list of expressions, in either comma-delimited (Write)or space delimited format.
Several points must be remembered...
To change betweenInput, Output andAppendmodes the file must be closed and
re-opened in the new mode.
A file must exist before it is opened forInput orAppend. Output mode creates anew 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 SeekSo, 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 1If LOF(1) > 30000 Then
Msg = The file is too largeMsgBox Msg, 16, File too Big
ElsetxtMainText.Text = Input$(LOF(1), 1)
End IfClose 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 1Print #1,txtMainText.Text
Close 1...
-
8/9/2019 Visual Basic 5-6 Course Part 5
8/21
Visual Basic Book 5 Mark Collins 1999 Page 7
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-defineddata- types for brevity and accuracy.
Random-Access Files
This file type (otherwise known as simplyRandom) is generally used to store a series ofidentical length records. Eachrecordmust 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 yourdata types, but it is easier to use a function that works that out for you LEN. Thisinformation is required when you open the file.
The main feature of this file access method is that you can read and write records whereverthey 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/
Statement
Description
Open Allows you to open a Random file.
Openfilefor Random AsfilenumberLen=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 givenvariable. e.g.
putfilenumber, Position, Variable
Several points need to be considered...
To add a new record you need toPut it in the position one more than the currentnumber 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 recordand taken care of later.
All strings (even within user defined types) must be of fixed lengths.
-
8/9/2019 Visual Basic 5-6 Course Part 5
9/21
Visual Basic Book 5 Mark Collins 1999 Page 8
The files are not easily interchangeable with other applications.
Example
Firstly a record type needs to be defined.Type Employee
Name As StringAge As IntegerSalary 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 onlyproblem is to make sure that you always read and write in a consistent manner as the
restrictions of the other types arent around to control matters.If you do store record type information within binary files you have both the advantage anddisadvantage of variable length records. Variable length records can save space, but theyrequire a lot more handling.
You use Get andPut similar to Random files, but you can get and put any length variable atany 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 Getstatement, 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 savethem, but there are controls to help you select the file names, directories and drives.
-
8/9/2019 Visual Basic 5-6 Course Part 5
10/21
Visual Basic Book 5 Mark Collins 1999 Page 9
Common Dialog Box ControlThe simplest way to select a file either to open or save is to use the Common Dialog BoxControl. 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 theydo 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 beresized and does not appear at runtime. The control has several important properties.
Action Property
The type of dialog box displayed is determined by theAction 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 ofDialog 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 thefilename unless otherwise specified.
-
8/9/2019 Visual Basic 5-6 Course Part 5
11/21
Visual Basic Book 5 Mark Collins 1999 Page 10
Filter / FilterIndex Properties
Available as an alternative / complement to the DefaultExt property and is used in both Open
and Save As dialogs. TheFilter property allows you to define several file filters thatdetermine which files are shown in the file list. The property actually contains a string withthe 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 theList 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 bitpatterns that can be combined using the Or operator in a bit-wise context. See the table in theAppendix for the full set.
An example of their use would be...CMDialog1.Flags = OFN_SHOWHELP OrOFN_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 ControlsThere will be times when the versatile Common Dialog Box Controlis not suitable for somefile 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
-
8/9/2019 Visual Basic 5-6 Course Part 5
12/21
Visual Basic Book 5 Mark Collins 1999 Page 11
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 hasList,ListIndex andListCount 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 theselected drive. It is only available atrun-time.
By selecting a drive from the list thedrive property contains the drive letter. Alternatively youcan set the drive by assigning it a string. Note that it only takes the first character, which isuseful in that we can assign a whole path string from which it picks the relevant information.
ChDrive drvSelectDrive.Drive SetCurrent Drive to selection
drvSelectDrive.Drive = CurDir$ SetControl Drive to Current drive
Directory List Box Control
We cant 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 displayitems 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~subdirectoryrelationships. The directories can be browsed through by using the mouse to move up anddown the directory tree.
-
8/9/2019 Visual Basic 5-6 Course Part 5
13/21
Visual Basic Book 5 Mark Collins 1999 Page 12
Path Property
This property determines the current absolute path, including the drive name and like the
Drive ControlsDrive 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 Pathproperty generates a Change event.
Examples of its use are...dirSelectDir.Path = F:\BIN\DATAdrvSelectDrive.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 thecurrent 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 toconsider.
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. ThePath
property is virtually identical to theDirectory List Box property of the same name and
contains the same level of detail. In this context it identifies the current directory from whichto display files.
ThePattern property then filters out the file names to appear based upon their names. Thedefault 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 listbased 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.
-
8/9/2019 Visual Basic 5-6 Course Part 5
14/21
Visual Basic Book 5 Mark Collins 1999 Page 13
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 boxand 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 linkin atext box too.
Basically when one of the controls changes you need to have processing in place to changethe others if necessary. The system helps in that when you change the path in thedirectory listthe 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 thedirectory list and activates ...Sub dirX_Change()
filX.Path = dirX.Path...
End Sub
Which in turn updates thefile list.
The possibility exists that using a text box or whatever we change thefilename property oftheFile list, including new drive and directory information. This automatically changes the
Path property of theFile list. In this case we need to possibly update the other controls...Sub filX_Change()
dirX.Path = filX.PathdrvX.Drive = filX.Path takes first
letter...
End Sub
-
8/9/2019 Visual Basic 5-6 Course Part 5
15/21
Visual Basic Book 5 Mark Collins 1999 Page 14
Appendix
Common Dialog Flag Property Constants
Constant Value Description
cdlOFNAllowMultiselect
&H200 Specifies that the File Name list box allows multipleselections. The user can select more than one file at run time
by pressing the Shift key and using the Up and Down Arrowkeys to select the desired files. When this is done, theFileName property returns a string containing the names ofall selected files. The names in the string are delimited byspaces.
cdlOFNCreatePrompt &H2000 Specifies that the dialog box should ask if the user wants tocreate a file that does not currently exist. This flagautomatically sets the cdlOFNPathMustExist and
cdlOFNFileMustExist flags.
cdlOFNExtensionDifferent
&H400 Indicates that the extension of the returned file name isdifferent from the extension specified by the DefaultExtproperty. This flag is not set if the DefaultExt property isNull, if the extensions match, or if the file has no extension.This flag value can be checked upon returning from thedialog box.
cdlOFNFileMustExist &H1000 Specifies that the user can enter only names of existing filesin the File Name text box. If this flag is set and the user entersan invalid file name, a warning is displayed. This flagautomatically 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 itwas when the dialog box was invoked.
cdlOFNNoReadOnlyReturn &H8000 Specifies that the returned file will not have the Read Onlyattribute set and will not be in a write-protected directory.
cdlOFNNoValidate &H100 Specifies that the common dialog box allows invalidcharacters in the returned file name.
cdlOFNOverwritePrompt
&H2 Causes the Save As dialog box to generate a message box ifthe selected file already exists. The user must confirmwhether to overwrite the file.
cdlOFNPathMustExist &H800 Specifies that the user can enter only valid path names. If thisflag is set and the user enters an invalid path name, a warningmessage is displayed.
cdlOFNReadOnly &H1 Causes the Read Only check box to be initially checked whenthe 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.
-
8/9/2019 Visual Basic 5-6 Course Part 5
16/21
-
8/9/2019 Visual Basic 5-6 Course Part 5
17/21
Visual Basic Book 5 Mark Collins 1999 Page 16
Private Sub cmdDelete_Click()
If FileCheck = TrueThen
Kill ("c:\temp\test.seq")
End If
txtMainText.Text = ""
End Sub
Private Sub cmdRead_Click()
Dimmsg As String
DimdispAs String
If FileCheck = True Then
Open "C:\temp\test.seq" For Input As 1If 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.TextClose 1
End If
txtMainText.Text = ""
End Sub
-
8/9/2019 Visual Basic 5-6 Course Part 5
18/21
Visual Basic Book 5 Mark Collins 1999 Page 17
Private Function FileCheck()
Dimvalue As Boolean
Dimmsg 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 isparticularly important when dealing data files?
Add extra features to enable only the appropriate buttons when file exists/ not exists, etc.
-
8/9/2019 Visual Basic 5-6 Course Part 5
19/21
Visual Basic Book 5 Mark Collins 1999 Page 18
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 its size, that will be dealtwith 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 toactivate this when we Load the Form and if we resize it. Place it inForm_Resize and
call it fromForm_Load.
Sub Form_Resize ()txtMainText.Left = 0
txtMainText.Top = 0txtMainText.Width = frmTextEdit.WidthtxtMainText.Height = frmTextEdit.Height
End Sub
Sub Form_Load ()Form_Resize
End Sub
Also set up a single declared variable in General / declarationsDimFilenameAs String
5 Next we need controls to open and save our text, not forgetting exiting. Time to add amenu.
ActivateMenu Design Box by right-mouse clicking on the form
Create a new entry with the caption &File, call it mnuFile
ClickNext followed by the right arrow button. Give this new submenu thecaption &Open... and the namemnuFileOpen
ClickNext once more, give its entry caption Save &As... and the name
mnuFileSave
ClickNext again, place a single hyphen in the Caption and give it the name
mnuSep
-
8/9/2019 Visual Basic 5-6 Course Part 5
20/21
Visual Basic Book 5 Mark Collins 1999 Page 19
ClickNext 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 atdesign-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.FilenameIf Filename "" Then
Open Filename For Input As 1If LOF(1) > 30000 Then
Msg = "The file is toolarge"
MsgBox Msg, 16, "File tooBig"
ElsetxtMainText.Text =
Input$(LOF(1), 1)End If
End IfClose 1
End Sub
Sub mnuFileSave_Click ()CMDialog1.DialogTitle = "Save
As..."
CMDialog1.Action = 2Filename$ = CMDialog1.FilenameOpen Filename For Output As 1Print #1, txtMainText.TextClose 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 isalways a good thing...)
8 Your turn. Develop your editor so that...
A second menu heading captioned &Text is added with sub-menus &Boldand
&Italic. Try attaching sensible shortcut keys to these. Their code simply switches
bold and italic on and off in the text box. Make sure acheck (tick) appears besidethe menu item when switched on.
-
8/9/2019 Visual Basic 5-6 Course Part 5
21/21
Visual Basic Book 5 Mark Collins 1999 Page 20
How about inserting anEdit section after the File section. Build in some simplecut, 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.
top related