File Handling


*  How to handle files?
*  Statements related to file handling
*  Functions related to file handling
*  File controls - FileListBox, DirListBox and DriveListBox.
*  Sample application using file control and file related functions
A file is a collection of bytes stored on the disk with a given name (called as filename). Every development tool provides access to these files on the disk.  In this chapter we will understand how to access and manipulate files using Visual Basic.

There are three special controls, called as File controls, which deal with files and directories. We will also understand how to use these controls in this chapter.

File handling
The following are three important steps in handling a file.

¨         Opening the file
¨         Processing the file, i.e. either reading the content of the file or writing the required data into file or both.
¨         Closing the file
File access types
Depending upon the requirement you can use any of the three different file access types:

Sequential
For reading and writing text files in continuous blocks.
Random
For reading and writing text or binary files structured as fixed-length records.
Binary
For reading and writing arbitrarily structured files.

Opening the file using Open statement
A file is opened using OPEN statement in Visual Basic. At the time of opening a file, you have to specify the following.

¨         Name of the file to be opened
¨         The mode in which file is to be opened. The mode specifies which operations are allowed on the file.
¨         File number. Each open file contains a file number.  This file number is used to access the file once the file is opened.  The file number must be unique.
Open pathname For mode [Access access] [lock] As [#] filenumber [Len=reclength]

Option
Meaning
Pathname
Name of the file to be opened.
Mode
Specifies the mode in which file is to be opened. Valid modes: Append, Input, Output, Binary and Random. If unspecified then Random is taken.
Access
Specifies the operations that are permitted on the open file.  Valid values: Read, Write, or ReadWrite.
Lock
Specifies the operations restricted on the file opened by other users. Value values: Shared, Lock Read, Lock Write, and Lock Read Write.
Filenumber
A number in the range 1 to 511. This number must be unique among open files. Use FreeFile function to obtain the next available number.
RecLength
Specifies the size of each record in random files.  It should be <= 32767. For sequential files, this is the number of characters buffered. This is ignored, if mode is Binary.
If the file is not existing then a new file with the given name is created in Append, Binary, Output and Random modes.

Examples:

To open TEST.TXT file in input mode:

Open “TEST.TXT” for input as #1

To open NUMBER.DAT file in Binary mode:

Open “NUMBER.DAT” for binary access write as #1

To open STUDENTS.DAT in random mode with a record length of 10:

Open  “STUDENTS.DAT” for random as #1 len = 10

To get next available file number and then use it:

'FreeFile function returns the number that can be used as the file 'number while opening the file

Fn = FreeFile
Open “TEST.TXT” for input as #fn

Functions related to files
The following are the functions that are used with files.

Function
Meaning
Dir
Returns the name of the file that matches the given name. If file is not existing then it returns "" (null string).
FileLen
Returns the length of the file in bytes.
LOF
Returns the length of an open file in bytes.
EOF
Returns true, if the specified file has reached end-of-file marker.
FreeFile
Returns the next available file number.
Seek
Sets or returns the position at which file pointer is currently positioned. For random files it returns the number of records read or written so far.
Filecopy
Copies the given source file to target file.
GetAttr
Returns the attributes of the given path.
SetAttr
Changes the attributes of the specified file to the given attributes.
FileDateTime
Returns the date and time when file was last modified or created.
Loc
Returns the current position of file pointer of an open file.
Table 10.1: Functions related to file handling.

Example:

To find out the length of file CHARS.TXT:

fl = FileLen("c:\vb60\chars.txt")

 

To find out whether file with the file number 1 has reached end-of-file:

if EOF(1) then
    
end if

To check whether STUDENTS.DAT file is existing or not:

If  dir(“students.dat”)  = “” then
   MsgBox  “File students.dat is missing”
Else
   Process the file
End if

Statement related to file Input and output
The following statements are used to perform input or output to file and other operations such as opening and closing.

Statement

Meaning

Close
Closes an open file
Get
Read a record from the given position of the specified file.
Input( )
Returns the specified number of characters from the given file.
Input #
Reads data into specified list of variables from the given file.
Line Input #
Reads a complete line from the given file.
Open
Opens the given file in the specified mode.
Print #
Prints the specified data to the given file.
Put
Writes a record to the given position of the specified file.
Write #
Writes the specified data to the given file.
Table 10.2: Statements related to file handling.


Not all statements are available in all modes. So, the following table shows the availability of each statement in each of the three access types.

In the table X denotes the availability of the command in the mode.

Statement

Sequential
Random
Binary
Close
X
X
X
Get

X
X
Input( )
X

X
Input #
X


Line Input #
X


Open
X
X
X
Print #
X


Put

X
X
Write #
X

`
Table 10.3: The availability of the statements in three access modes.

Note: See chapter 12, to understand how to use statements related to sequential files. Detail discussion of Random and Binary files is beyond the scope of this material. Please see on-line documentation if you are interested.

File Controls
Visual Basic provides a set of controls, which are used to display files, directories and drives. These controls are part of standard controls. The following are the file controls and what they do.

Control
Meaning
FileListBox
Displays a list of files. This is a listbox that displays list of files from the path specified using Path property.
DirListBox
Displays hierarchical list of directories.
DriveListBox
Displays the list of drives available in the system.
Table 10.4: File controls.


Properties and Events of FileListBox
The following are specific events and properties of FileListBox.

Type
Name
Meaning
Property
Filename
Contains the name of the file selected by user.

Path
Contains the name of the directory from where list of files is taken.

Pattern
Specifies the pattern that is used to filter filenames, such as *.exe.

System
Specifies whether system files are to be displayed or not.

Readonly
Specifies whether readonly files are to be displayed or not.

Hidden
Specifies whether hidden files are to be displayed or not.

Archive
Specifies whether archive files are to be displayed or not.
Event
Pathchange
Occurs whenever path is changed.

Patternchange
Occurs whenever pattern is changed.
Table 10.5: Properties and events that are specific to FileListBox


Note: FileListBox also has properties that are available for listbox, such as MultiSelect, ListCount etc., but it doesn’t have the methods that are found with listbox, such as Additem.


Sample Application
Let us develop an application that used file controls and file-related functions. This application allows user to select a file from any directory and drive using three file-related controls mentioned above. Once user selects a file, details of the selected file, such as length, attributes and date of last modification will be displayed.

The following are the steps required to create the sample application.

1.      Start a new project using File-> New Project and select Standard Exe as the project type.
2.      Place FileListBox, DirListBox and DriveListBox on the left of the form
3.      Place three label controls to display messages File, Directories and Drives at the top of each of the controls created in the previous step.
4.      Place a Frame control on the right of the form.
5.      Place a collection of label controls. These label controls are used to display the information regarding file.
6.      Also place a Listbox. This is used to display the attributes of the file.  A listbox is selected because a file may contain more than one attribute, such as Readonly, Hidden etc.
7.      Place a command button at the bottom. This is used to quit the application.
8.      Arrange all controls

Note:  A frame is used only to group controls physically to show that all the controls are related.

Changing properties
After having placed required controls on the form, now let us concentrate on changing required properties to get required appearance and functionality.

First let us concentrate on the properties of file controls.  For Directory list box and Drive list box no property needs to be changed. But for File list box some properties are to be changed in order to display all types of files. By default only files of type Archive and Read-only only will be displayed. But as we want to display all types of files, we have to set Hidden and System properties to True. Remember by default Archive and ReadOnly properties are already set to True.

The following table lists out the properties to be changed for all other controls on the form.

Control
Property
Value
Frame1
Caption
Details

Fontbold
True
Label1
Caption
Files
Label2
Caption
Directories
Label3
Caption
Drives
Label4
Caption
Filename
Label5
Name
Lblname

Caption
“”

Borderstyle
1-Fixed Single
Label6
Caption
Size
Label7
Name
Lblsize

Caption
“”

Borderstyle
1-Fixed Single
Label8
Caption
Attributes
Label9
Caption
Last Updated
Label10
Name
Lbldate

Caption
“”

Borderstyle
1-Fixed Single
List1
Name
Lstattributes
Command1
Name
Cmdquit

Caption
&Quit


Note: The default names of the label control may not exactly match the names of your label controls, if the order in which you created the label control is different. change the properties.

Writing Code to connect file controls
At this stage, if you run the project and select a different directory, it doesn’t change the list of files. But it should. In the same way if you select a different drive, it doesn’t change the list of directories. But again it should. So, we first concentrate on connecting these three controls. That means when user changes the drive, then automatically directory list box should display the list of directories from new drive. The same is true with selecting a different directory in directory list box (it should change list of files in file list box).

Whenever user changes the selection of drive, Change event occurs for Drive list box. Take the drive selected by user using Drive property of DriveListBox and set it to Path property of DirListBox. Then DirectoryListBox will get the list of directories from new drive. Here is the code to do that.

Private Sub Drive1_Change()

  Dir1.Path = Drive1.Drive
 
End Sub
Listing 10.1: Code to connect drive list box with directory listbox.

Whenever user select a different directory,  Change event for DirListBox occurs. Take new path and assign that value to Path property of FileListBox to get new list of file from newly selected directory. Here is the code to do that.

Private Sub Dir1_Change()

    File1.Path = Dir1.Path

End Sub
Listing 10.2: Code to connect DirListBox to FileListBox.

Now let us get to crux. Whenever user selects a file in FileListBox, we have to display information regarding the selected file. The information is, Full name of the file, Size of the file, Attributes of the file and Date and time on which the file was last updated.

Getting size and date of last updation is quite simple. It is just a matter of using FileLen and FileDateTime functions.

Getting full filename is also done except in one case. Path property of FileListBox contains the path in which file is existing. Filename property contains the name of the file. So to get complete filename we have to concatenate these two values. As path is to be separated from filename using a backslash (\), we also have to concatenate a backslash after path. However, when path is referring to root directory, backslash is already there in the path. Adding an extra backslash is going to make path invalid. So we have to see whether the last character is a backslash. It can be done by taking the right most character using Right function and comparing it with backslash. Only when the rightmost character is not a backslash we add backslash at the end of path. Listing 10.3, show the code to do this.

Attributes of a file can be obtained using GetAttr function. But this function returns an integer, which is to be decoded to get information regarding attributes. The value returned by GetAttr is to be bitwise Anded with predefined numbers to know the attributes of the file. For example, to know whether file is readonly or not we have to use bitwise And operator to perform bitwise Anded between the value returned by GetAttr and constant vbReadOnly.

We will write a procedure that takes the attributes integer and a listbox. The procedure determines the attributes of the file and adds items with attribute names to listbox. We name this procedure as GetFileAttributes.  Listing 10.4, show this procedure.

Private Sub File1_Click()

Dim fn As String

  ' form complete filename

  fn = File1.Path

  ‘ if rightmost character is not backslash then add a backslash

  If Right(File1.Path, 1) <> "\" Then
        fn = fn & "\"
  End If
 
  fn = fn & File1.FileName
 
  lblname.Caption = fn
 
  lblsize.Caption = FileLen(fn)
  lbldate.Caption = FileDateTime(fn)
 
  ‘ call procedure to populate listbox with attributes of the file
  GetFileAttributes GetAttr(fn), Lstattributes
End Sub
Listing 10.3: Code for click event of File control.

Public Sub GetFileAttributes(attr As Integer, lstbox As ListBox)

  ‘clear all items from listbox
  lstbox.Clear
 
  ‘check for read-only attribute
  If (attr And vbReadOnly) <> 0 Then
        lstbox.AddItem "Read Only"
  End If
  ‘ check for Hidden attribute
  If (attr And vbHidden) <> 0 Then
        lstbox.AddItem "Hidden"
  End If
 ‘check for System attribute
  If (attr And vbSystem) <> 0 Then
        lstbox.AddItem "System"
  End If
 ‘check for Archive attribute

  If (attr And vbArchive) <> 0 Then
        lstbox.AddItem "Archive"
  End If
 
End Sub
Listing  10.4: Code for GetFileAttributes user-defined procedure

Also write code for Quit button, which contains a single statement which is Unload Me.

Test Run
Now run the project by pressing F5. First you see list of files from current directory. Change directory by double clicking on a new directory in the Dirlist box. This should change the list of files. Also test whether a change in drive list box is changing the list of directories.

If you select root directory and the select IO.SYS

You can enhance the application by adding a button to display the content of the selected file. However, for this you need to take only text files (files that are readable) into account.

System Objects



*  What are the system objects?
*  Screen object
*  Clipboard object
*  Printer object
*  Debug object
*  App object
System objects allow you to access system resources like Clipboard, and Screen etc.  Visual Basic allows you to access the system resources through properties and methods of the system objects. The following is the list of system objects and what they do. Detailed discussion about each system object will follow.

System Object
Description
Screen
Allows you to access properties of screen such as width, height, fonts available screen etc.
Printer
Allows you to access the default printer.
Clipboard
Allows you to place data on clipboard and take data from clipboard.
App
Lets you access important information regarding the current application.
Debug
Allows you to send output to immediate window at runtime.
Table  11.1: System objects.

The following section will discuss each of the system objects in detail.

Screen Object
Allows you to access screen-related properties. Screen object is accessed using keyword Screen.
The following are the various properties of Screen object.

Property

Description

ActiveControl
Returns the control that currently has focus.
ActiveForm
Returns the form that currently has focus.
FontCount
Returns the number of fonts available for the display device.
Fonts()
This is an array that contains the names of all the available fonts for display device.
MousePointer
Determines the type of mouse pointer to be used.
MouseIcon
Contains the custom mouse icon. This is taken when MousePointer property is set to vbCustom.
Height and Width
Returns the size of the screen in Twips.
TwipsperpixelX , TwipsperpixelY
Return the number of twips per pixel on the screen.

Table 11.2: Screen object properties.

The following snippets of code demonstrate how to use screen object.

To get the list of fonts supported by the display device place them in a list box, enter:

For I  = 0 to screen.fontcount –1
      List1.additem (screen.fonts(I))
Next


To change mouse pointer to a custom mouse pointer, enter:

Screen.mouseicon  = LoadPicture(“arrow.ico”);
Screen.mousepointer = vbCustom

To center the form on the screen, enter the following code in FORM_LOAD event:

Private Sub Form_Load()
Dim x as integer, y as integer

   x = (Screen.Width - Me.Width) / 2
   y = (Screen.Height - Me.Height) / 2
   Me.Move x, y
End Sub

Printer Object
Printer object allows you to print to default printer. The following are the important properties of Printer object.

Property

Meaning

Copies
Specifies the number of copies to be printed. Default is 1.
ColorMode
Determines whether a color printer prints output in color or monochrome. Valid options are: 1 – monochrome, 2 – color. If the printer is monochrome then it ignores this property.
Devicename
Returns the name of the device.
Drivername
Returns the name of the driver
Orientation
Indicates whether documents are printed in portrait or landscape mode.
1 – portrait, 2 – landscape.
Page
Returns the current page number.
PaperSize
Returns or sets a value indicating the paper size for the current printer Please see on-line help for valid options.
PaperBin
Indicates the bin on the printer from which paper is fed when printing. Please see on-line help for valid options.
Printquality
Returns or sets a value indicating the printer resolution. Valid options are:
-1 Draft, -2 Low, -3 Medium, -4 High. 
You can also set this property to dots per inch (DPI), like 300.
Zoom
Returns or sets the percentage by which printed output is to be scaled up or down. Default is 0, which means normal size.
Table 11.3: Properties that are unique to Printer Object

Printer object also has collection of methods. While properties are used to change the settings, methods are used to actually print and control printing operations.

Following are the methods that are specific to Printer object. Remember Printer object has some of the common methods such as Circle, Line etc. But in this section, I will discuss about only the methods that are specific to Printer object. For complete list, please see on-line help.

Method

What it does?

EndDoc
Terminates a print operation sent to the printer using Printer object and releases the document to the print device or spooler. Printing will not start unless you execute EndDoc.
KillDoc
Terminates the current print job immediately.
NewPage
Ends the current pages and advances to the next page.
Print
Prints the given text to printer.
Table 11.4: Methods that are specific to Printer object.

The following are various examples regarding how to use Printer object properties and methods.

To display two lines in draft resolution mode, enter:

Printer.PrintQuality = -1  'draft resolution
Printer.Print "Who is the author of this book?"
Printer.Print "P.Srikanth"
Printer.EndDoc

To display two lines in two different pages with various other setting, enter:

Printer.CurrentX = 0
Printer.CurrentY = 0
Printer.colromode = 2  ' put in color mode
Printer.Orientation = 2 ' landscape
Printer.Zoom = 100       ' double the size
Printer.Print "This is at the uppper-left corner"
Printer.NewPage        ' go to next page
Printer.Print "This is in the second page"
Printer.EndDoc

App object
App object contains important information regarding the current application such as  help file to be used, whether previous instance of this application is running etc.

The following are the important properties of App object. For the complete list of properties, please see on-line help for App object.

Property

Meaning

ExeName
Returns the root name of the executable file (without the extension) that is currently running. If running in the development environment, returns the name of the project
Taskvisible
Returns or sets a value that determines if the application appears in the Windows task list.
HInstance
Returns a handle to the instance of the application. If project is run in IDE, returns the handle of the IDE.
LogMode
Specifies how logging  is to be carried out.
LogPath
Specifies the path and file name to which logging information should be written.
UnAttendedApp
Returns a value that determines if an application will run without any user interface.
Helpfile
Specifies the path and filename of a Help file used by your application to display Help or online documentation.
PrevInstance
Returns a value indicating whether a previous instance of the application is already running.
Startmode
Returns or sets a value that determines whether an application starts as a stand-alone project or as an ActiveX component.
0 – Standalone, 1 - ActiveX component.
Table 11.5:  Properties of App object.

The following are the available methods of App object.

Method

What it does?

Logevent logbuffer, eventtype
Logs an event in the application's log target, which is specified using LogPath property.
Logbuffer is the message to be logged.
EventType is: 1-error, 2-warning, 4 – information.
StartLogging logTarget, logMode
Sets the log target and log mode of an operation.
Table 11.6:Methods of App object.

To test whether application has started as a standalone or as an ActiveX component:

If App.StartMode = 0 then
   ‘do what you want for    standalone application
Else
    'do what you want for ActiveX component
End if

To prevent second instance from starting:

If not IsNull (App.PrevInstance) then
     Unload me
End if
 
Debug Object
Allows you to write to immediate window. This object is meaningful only when project is run in development environment. At run time Debug object is ignored.

The following are the methods available in Debug object.

Method

What it does?

Print
Prints the given text to Immediate window.
Assert
Suspends the execution at the line where method appears if the given condition is false. If the condition is true, it has no effect on execution.
Table 11.7: Methods of Debug object.

To suspend the execution of program if the value of variable amount is more than 10000, enter:

Debug.Assert amount > 10000

To print the value of variable amount to immediate window, enter:

Debug.Print  amount
Note: you can suspend execution of the program using stop method by pressing Ctrl + Break in VB IDE

Clipboard Object
Allows you to access system clipboard. Visual Basic applications can place data on to clipboard so that other applications can receive the data. In the same way it is also possible to receive data that is currently  placed on clipboard. The following are the available methods in clipboard.

Method

What it does?

Settext
Places the given text on the clipboard.
Setdata 
Places the given binary data, such as pictures, on the clipboard.
Gettext
Returns the text that is currently on clipboard.
Getdata
Returns the data that is currently on clipboard. This is used to retrieve binary data such as pictures.
Clear
Clears data that is on clipboard.
Getformat
Returns true if clipboard contains the data of the specified format. Please see on-line help for the list of valid formats.
Table 11.8: methods of Clipboard object.

Sample Application
It is time to consolidate. Let us develop an application that can place data on the clipboard or send the data to printer. The sample application displays the list of available fonts so that user can format the text before printing.  The application also takes care of enabling and disabling options such as cut and paste automatically.

user-interface of the application the following is the menu structure and what each menu item does.

Option

What it does?

Cut
Places the text that is currently selected in text box to clipboard. And removes the selected text from textbox.
Copy
Places the text that is currently selected in textbox to clipboard.
Paste
Copies the text that is currently available in clipboard at the cursor position in textbox. If any text is selected in text box then the text from clipboard replaces the selected text of the textbox.
Table 11.9: Meaning of options in Edit menu.
Let us now understand what these controls on the form do?

Text Box

Allows user to enter the text that can be sent either to clipboard or to printer. It supports multiple lines and also contains scrollbars.
First Combobox
Display the list of fonts available from Screen object. Initially it is set to font “Arial”. Whenever user selects a new font, the text in textbox will be displayed in the new font.

Second Combobox

Allows you to select a size for font. It displays number in the range 6 to 50 with an increment of 2. User is allowed to either select a number from the list. User is also allowed to enter a new value. The text in the textbox will be displayed in the new size.

Print command button

Prints the text that is in textbox in the selected font and with the selected size to default printer.  It uses Printer object to send text to printer.

Creating the sample application
The following are the steps to be taken to develop the sample application.

1.       Create a new project using File-> New Project and select Standard Exe as the type of the project.
2.       Place the required control
3.       Change the properties as shown in the table below.

Object
Property

Value

Form
Caption
System Objects Demo
Label1
Caption
Print Text
Text1
Name
Txtsample

Multiline
True

Scrollbars
3 –both

Text
“ “ ( Null string)
Combo1
Name
Cmbfonts

Style
2-dropdown list
Combo2
Name
Cmbsize
Command1
Name
Cmdprint

Caption
&Print
Command2
Name
CmdQuit

Caption
&Quit

Write code for Form_Load event to add the names of the available fonts using Screen object. Also add numbers in the range 6 to 50 with an increment of 2.


Private Sub Form_Load()
  'Load fonts from Screen objects
  For i = 0 To Screen.FontCount - 1
     Cmbfonts.AddItem Screen.Fonts(i)
  Next
  Cmbfonts.Text = "Arial"    ‘ select Arial as the default font
  'add numbers with increment of 2 to cmbsize
  For i = 6 To 50 Step 2
    cmbsize.AddItem i
  Next
  ‘select 6 as the default size
  cmbsize.ListIndex = 0
End Sub
Listing 11.1: Code for Load event of the form object.

Now let us write code to change the name of the font whenever user selects a new font name in ComboBox.

Private Sub Cmbfonts_Click()
  txtsample.Font.Name = Cmbfonts.Text
End Sub
Listing 11.2: Code for Click event of cmbFonts combo box.

Text property contains the name of the font currently selected. Use Name attribute of Font object to change the name of the font for textbox.

In the same way let us write code to change size of the font whenever user selects a different size using size Combobox. But as this is a dropdown combo box, user can also directly enter text into it. So after user enters the size, the new size should be used to change the size of text in textbox. For this we use LostFocus event of the Combobox. LostFocus event occurs when user is moving out of the Combobox.

So we have to write code for two events of size Combobox. Listing 11.3 shows the code for size combo box (cmbsize).

Private Sub cmbsize_Click()
 txtsample.Font.Size = Val(cmbsize.Text)
End Sub
Private Sub cmbsize_LostFocus()
 txtsample.Font.Size = Val(cmbsize.Text)
End Sub
Listing 11.3: Code for Size ComboBox.

Whenever user clicks on Print command button, the text that is entered by the user in the textbox should be printed using the selected font name and font size. The code in listing 11.4, accomplishes that task.
Private Sub cmdprint_Click()
   ‘ Change font name and font size of the printer object so that
   ‘ text that is printed is printed with those attributes
   Printer.Font.Name = Cmbfonts.Text
   Printer.Font.Size = Val(cmbsize.Text)
   Printer.Print txtsample     ‘ send text to printer
   Printer.EndDoc              ‘ indicate end of printing job
End Sub
Listing 11.4: Code for Print command button
Let us also complete code for quit buttons.

Private Sub cmdquit_Click()
  Unload Me
End Sub
Listing 11.5: Code for Quit button.

At this stage run the project and test whether changing font name in Combobox is changing the font of the text in textbox. Also test whether changing size is changing the size of character in textbox. Also test whether typing size in size Combobox and moving out of it is changing the size of the character.

If all tests are successful then proceed to next section, otherwise find out the bug and debug it. Remember, nobody is a born programmer. Programming is learnt by writing programs. Initially your program may not be successful. But finding out errors and correcting them is all what programming is all about. So do it.

Writing code for Edit menu
Now let us turn our attention to Edit menu. Options in Edit menu are used to place text in clipboard and retrieve text from clipboard.

First let us concentrate on Cut option. When user selects Cut option, the following steps are to be taken.

¨         Place the selected text of the textbox on Clipboard
¨         Delete the text that is selected.

We use SelText property of the textbox. SelText property of the textbox contains the text that is currently selected (highlighted).
Note: If no text is selected then SelText refers to current position in the textbox.

Here is the code for Cut option of edit menu.

Private Sub mnucut_Click()

'copy the selected text on to clipboard
Clipboard.SetText txtsample.SelText
'cut the selected text
txtsample.SelText = ""

End Sub
Listing  11.6: Code for Cut option.

Copy option also does the same as Cut option except that it doesn’t delete the selected text. Here is the code for copy option.

Private Sub mnucopy_Click()
 'copy the selected text on to clipboard
 Clipboard.SetText txtsample.SelText
End Sub
Listing 11.7: Code for Copy option.
Paste option takes the text that is in the clipboard and places it either at the current position, if nothing is selected, or replaces the selected text. Both the purposes can be served using SelText property of textbox. Listing 11.8, shows the code for Paste option.

Private Sub mnupaste_Click()
   ‘ get text from clipboard and replace selected text
   ‘ or place it at the cursor position if not text is selected
   txtsample.SelText = Clipboard.GetText
 
End Sub
Listing 11.8: Code for Paste option.

The next and last step is automatically enabling and disabling options in Edit menu depending upon the context. That means if no text is selected then Cut and Copy options are to be disabled. In the same way if no text is existing in clipboard then Paste option is to be disabled.

That means Cut and Copy are enabled only when text is selected in textbox.

Paste option is enabled only when clipboard contains text.

The following is the code for click event of Edit menu. Click event of Edit menu is the place where you have to enable or disable because, click event occurs before menu is displayed to user.

Note: But you cannot select click event of Edit menu in design mode like you can select for options. Because whenever you click on edit menu the options will be displayed but code window is not invoked. So get into code window and then select mnuEdit as the object and Click as the event and write the following code.

Private Sub mnuedit_Click()
  
' disable all options
mnucut.Enabled = False
mnucopy.Enabled = False
mnupaste.Enabled = False

If txtsample.SelText <> "" Then
    ' enable cut and copy options
    mnucut.Enabled = True
    mnucopy.Enabled = True
End If

‘ check whether clipboard has any text

 If Clipboard.GetFormat(vbCFText) Then
     mnupaste.Enabled = True
 End If

End Sub
Listing 11.9: Code for Edit menu.

GetFormat method of Clipboard object returns true if data in the clipboard is of the specified type. Here we are checking whether clipboard has any text, using  vbCFText constant. For the list of available constants and corresponding numeric values, please see on-line help for GetFormat method of Clipboard object.

System objects are useful in Visual Basic. They are used to access system devices. App does not refer to any device but it contains information regarding application.

File Handling


*  How to handle files?
*  Statements related to file handling
*  Functions related to file handling
*  File controls - FileListBox, DirListBox and DriveListBox.
*  Sample application using file control and file related functions
A file is a collection of bytes stored on the disk with a given name (called as filename). Every development tool provides access to these files on the disk.  In this chapter we will understand how to access and manipulate files using Visual Basic.

There are three special controls, called as File controls, which deal with files and directories. We will also understand how to use these controls in this chapter.

File handling
The following are three important steps in handling a file.

¨         Opening the file
¨         Processing the file, i.e. either reading the content of the file or writing the required data into file or both.
¨         Closing the file
File access types
Depending upon the requirement you can use any of the three different file access types:

Sequential
For reading and writing text files in continuous blocks.
Random
For reading and writing text or binary files structured as fixed-length records.
Binary
For reading and writing arbitrarily structured files.

Opening the file using Open statement
A file is opened using OPEN statement in Visual Basic. At the time of opening a file, you have to specify the following.

¨         Name of the file to be opened
¨         The mode in which file is to be opened. The mode specifies which operations are allowed on the file.
¨         File number. Each open file contains a file number.  This file number is used to access the file once the file is opened.  The file number must be unique.
Open pathname For mode [Access access] [lock] As [#] filenumber [Len=reclength]

Option
Meaning
Pathname
Name of the file to be opened.
Mode
Specifies the mode in which file is to be opened. Valid modes: Append, Input, Output, Binary and Random. If unspecified then Random is taken.
Access
Specifies the operations that are permitted on the open file.  Valid values: Read, Write, or ReadWrite.
Lock
Specifies the operations restricted on the file opened by other users. Value values: Shared, Lock Read, Lock Write, and Lock Read Write.
Filenumber
A number in the range 1 to 511. This number must be unique among open files. Use FreeFile function to obtain the next available number.
RecLength
Specifies the size of each record in random files.  It should be <= 32767. For sequential files, this is the number of characters buffered. This is ignored, if mode is Binary.
If the file is not existing then a new file with the given name is created in Append, Binary, Output and Random modes.

Examples:

To open TEST.TXT file in input mode:

Open “TEST.TXT” for input as #1

To open NUMBER.DAT file in Binary mode:

Open “NUMBER.DAT” for binary access write as #1

To open STUDENTS.DAT in random mode with a record length of 10:

Open  “STUDENTS.DAT” for random as #1 len = 10

To get next available file number and then use it:

'FreeFile function returns the number that can be used as the file 'number while opening the file

Fn = FreeFile
Open “TEST.TXT” for input as #fn

Functions related to files
The following are the functions that are used with files.

Function
Meaning
Dir
Returns the name of the file that matches the given name. If file is not existing then it returns "" (null string).
FileLen
Returns the length of the file in bytes.
LOF
Returns the length of an open file in bytes.
EOF
Returns true, if the specified file has reached end-of-file marker.
FreeFile
Returns the next available file number.
Seek
Sets or returns the position at which file pointer is currently positioned. For random files it returns the number of records read or written so far.
Filecopy
Copies the given source file to target file.
GetAttr
Returns the attributes of the given path.
SetAttr
Changes the attributes of the specified file to the given attributes.
FileDateTime
Returns the date and time when file was last modified or created.
Loc
Returns the current position of file pointer of an open file.
Table 10.1: Functions related to file handling.

Example:

To find out the length of file CHARS.TXT:

fl = FileLen("c:\vb60\chars.txt")

 

To find out whether file with the file number 1 has reached end-of-file:

if EOF(1) then
    
end if

To check whether STUDENTS.DAT file is existing or not:

If  dir(“students.dat”)  = “” then
   MsgBox  “File students.dat is missing”
Else
   Process the file
End if

Statement related to file Input and output
The following statements are used to perform input or output to file and other operations such as opening and closing.

Statement

Meaning

Close
Closes an open file
Get
Read a record from the given position of the specified file.
Input( )
Returns the specified number of characters from the given file.
Input #
Reads data into specified list of variables from the given file.
Line Input #
Reads a complete line from the given file.
Open
Opens the given file in the specified mode.
Print #
Prints the specified data to the given file.
Put
Writes a record to the given position of the specified file.
Write #
Writes the specified data to the given file.
Table 10.2: Statements related to file handling.


Not all statements are available in all modes. So, the following table shows the availability of each statement in each of the three access types.

In the table X denotes the availability of the command in the mode.

Statement

Sequential
Random
Binary
Close
X
X
X
Get

X
X
Input( )
X

X
Input #
X


Line Input #
X


Open
X
X
X
Print #
X


Put

X
X
Write #
X

`
Table 10.3: The availability of the statements in three access modes.

Note: See chapter 12, to understand how to use statements related to sequential files. Detail discussion of Random and Binary files is beyond the scope of this material. Please see on-line documentation if you are interested.

File Controls
Visual Basic provides a set of controls, which are used to display files, directories and drives. These controls are part of standard controls. The following are the file controls and what they do.

Control
Meaning
FileListBox
Displays a list of files. This is a listbox that displays list of files from the path specified using Path property.
DirListBox
Displays hierarchical list of directories.
DriveListBox
Displays the list of drives available in the system.
Table 10.4: File controls.


Properties and Events of FileListBox
The following are specific events and properties of FileListBox.

Type
Name
Meaning
Property
Filename
Contains the name of the file selected by user.

Path
Contains the name of the directory from where list of files is taken.

Pattern
Specifies the pattern that is used to filter filenames, such as *.exe.

System
Specifies whether system files are to be displayed or not.

Readonly
Specifies whether readonly files are to be displayed or not.

Hidden
Specifies whether hidden files are to be displayed or not.

Archive
Specifies whether archive files are to be displayed or not.
Event
Pathchange
Occurs whenever path is changed.

Patternchange
Occurs whenever pattern is changed.
Table 10.5: Properties and events that are specific to FileListBox


Note: FileListBox also has properties that are available for listbox, such as MultiSelect, ListCount etc., but it doesn’t have the methods that are found with listbox, such as Additem.


Sample Application
Let us develop an application that used file controls and file-related functions. This application allows user to select a file from any directory and drive using three file-related controls mentioned above. Once user selects a file, details of the selected file, such as length, attributes and date of last modification will be displayed.

The following are the steps required to create the sample application.

1.      Start a new project using File-> New Project and select Standard Exe as the project type.
2.      Place FileListBox, DirListBox and DriveListBox on the left of the form
3.      Place three label controls to display messages File, Directories and Drives at the top of each of the controls created in the previous step.
4.      Place a Frame control on the right of the form.
5.      Place a collection of label controls. These label controls are used to display the information regarding file.
6.      Also place a Listbox. This is used to display the attributes of the file.  A listbox is selected because a file may contain more than one attribute, such as Readonly, Hidden etc.
7.      Place a command button at the bottom. This is used to quit the application.
8.      Arrange all controls

Note:  A frame is used only to group controls physically to show that all the controls are related.

Changing properties
After having placed required controls on the form, now let us concentrate on changing required properties to get required appearance and functionality.

First let us concentrate on the properties of file controls.  For Directory list box and Drive list box no property needs to be changed. But for File list box some properties are to be changed in order to display all types of files. By default only files of type Archive and Read-only only will be displayed. But as we want to display all types of files, we have to set Hidden and System properties to True. Remember by default Archive and ReadOnly properties are already set to True.

The following table lists out the properties to be changed for all other controls on the form.

Control
Property
Value
Frame1
Caption
Details

Fontbold
True
Label1
Caption
Files
Label2
Caption
Directories
Label3
Caption
Drives
Label4
Caption
Filename
Label5
Name
Lblname

Caption
“”

Borderstyle
1-Fixed Single
Label6
Caption
Size
Label7
Name
Lblsize

Caption
“”

Borderstyle
1-Fixed Single
Label8
Caption
Attributes
Label9
Caption
Last Updated
Label10
Name
Lbldate

Caption
“”

Borderstyle
1-Fixed Single
List1
Name
Lstattributes
Command1
Name
Cmdquit

Caption
&Quit


Note: The default names of the label control may not exactly match the names of your label controls, if the order in which you created the label control is different. change the properties.

Writing Code to connect file controls
At this stage, if you run the project and select a different directory, it doesn’t change the list of files. But it should. In the same way if you select a different drive, it doesn’t change the list of directories. But again it should. So, we first concentrate on connecting these three controls. That means when user changes the drive, then automatically directory list box should display the list of directories from new drive. The same is true with selecting a different directory in directory list box (it should change list of files in file list box).

Whenever user changes the selection of drive, Change event occurs for Drive list box. Take the drive selected by user using Drive property of DriveListBox and set it to Path property of DirListBox. Then DirectoryListBox will get the list of directories from new drive. Here is the code to do that.

Private Sub Drive1_Change()

  Dir1.Path = Drive1.Drive
 
End Sub
Listing 10.1: Code to connect drive list box with directory listbox.

Whenever user select a different directory,  Change event for DirListBox occurs. Take new path and assign that value to Path property of FileListBox to get new list of file from newly selected directory. Here is the code to do that.

Private Sub Dir1_Change()

    File1.Path = Dir1.Path

End Sub
Listing 10.2: Code to connect DirListBox to FileListBox.

Now let us get to crux. Whenever user selects a file in FileListBox, we have to display information regarding the selected file. The information is, Full name of the file, Size of the file, Attributes of the file and Date and time on which the file was last updated.

Getting size and date of last updation is quite simple. It is just a matter of using FileLen and FileDateTime functions.

Getting full filename is also done except in one case. Path property of FileListBox contains the path in which file is existing. Filename property contains the name of the file. So to get complete filename we have to concatenate these two values. As path is to be separated from filename using a backslash (\), we also have to concatenate a backslash after path. However, when path is referring to root directory, backslash is already there in the path. Adding an extra backslash is going to make path invalid. So we have to see whether the last character is a backslash. It can be done by taking the right most character using Right function and comparing it with backslash. Only when the rightmost character is not a backslash we add backslash at the end of path. Listing 10.3, show the code to do this.

Attributes of a file can be obtained using GetAttr function. But this function returns an integer, which is to be decoded to get information regarding attributes. The value returned by GetAttr is to be bitwise Anded with predefined numbers to know the attributes of the file. For example, to know whether file is readonly or not we have to use bitwise And operator to perform bitwise Anded between the value returned by GetAttr and constant vbReadOnly.

We will write a procedure that takes the attributes integer and a listbox. The procedure determines the attributes of the file and adds items with attribute names to listbox. We name this procedure as GetFileAttributes.  Listing 10.4, show this procedure.

Private Sub File1_Click()

Dim fn As String

  ' form complete filename

  fn = File1.Path

  ‘ if rightmost character is not backslash then add a backslash

  If Right(File1.Path, 1) <> "\" Then
        fn = fn & "\"
  End If
 
  fn = fn & File1.FileName
 
  lblname.Caption = fn
 
  lblsize.Caption = FileLen(fn)
  lbldate.Caption = FileDateTime(fn)
 
  ‘ call procedure to populate listbox with attributes of the file
  GetFileAttributes GetAttr(fn), Lstattributes
End Sub
Listing 10.3: Code for click event of File control.

Public Sub GetFileAttributes(attr As Integer, lstbox As ListBox)

  ‘clear all items from listbox
  lstbox.Clear
 
  ‘check for read-only attribute
  If (attr And vbReadOnly) <> 0 Then
        lstbox.AddItem "Read Only"
  End If
  ‘ check for Hidden attribute
  If (attr And vbHidden) <> 0 Then
        lstbox.AddItem "Hidden"
  End If
 ‘check for System attribute
  If (attr And vbSystem) <> 0 Then
        lstbox.AddItem "System"
  End If
 ‘check for Archive attribute

  If (attr And vbArchive) <> 0 Then
        lstbox.AddItem "Archive"
  End If
 
End Sub
Listing  10.4: Code for GetFileAttributes user-defined procedure

Also write code for Quit button, which contains a single statement which is Unload Me.

Test Run
Now run the project by pressing F5. First you see list of files from current directory. Change directory by double clicking on a new directory in the Dirlist box. This should change the list of files. Also test whether a change in drive list box is changing the list of directories.

If you select root directory and the select IO.SYS

You can enhance the application by adding a button to display the content of the selected file. However, for this you need to take only text files (files that are readable) into account.

System Objects



*  What are the system objects?
*  Screen object
*  Clipboard object
*  Printer object
*  Debug object
*  App object
System objects allow you to access system resources like Clipboard, and Screen etc.  Visual Basic allows you to access the system resources through properties and methods of the system objects. The following is the list of system objects and what they do. Detailed discussion about each system object will follow.

System Object
Description
Screen
Allows you to access properties of screen such as width, height, fonts available screen etc.
Printer
Allows you to access the default printer.
Clipboard
Allows you to place data on clipboard and take data from clipboard.
App
Lets you access important information regarding the current application.
Debug
Allows you to send output to immediate window at runtime.
Table  11.1: System objects.

The following section will discuss each of the system objects in detail.

Screen Object
Allows you to access screen-related properties. Screen object is accessed using keyword Screen.
The following are the various properties of Screen object.

Property

Description

ActiveControl
Returns the control that currently has focus.
ActiveForm
Returns the form that currently has focus.
FontCount
Returns the number of fonts available for the display device.
Fonts()
This is an array that contains the names of all the available fonts for display device.
MousePointer
Determines the type of mouse pointer to be used.
MouseIcon
Contains the custom mouse icon. This is taken when MousePointer property is set to vbCustom.
Height and Width
Returns the size of the screen in Twips.
TwipsperpixelX , TwipsperpixelY
Return the number of twips per pixel on the screen.

Table 11.2: Screen object properties.

The following snippets of code demonstrate how to use screen object.

To get the list of fonts supported by the display device place them in a list box, enter:

For I  = 0 to screen.fontcount –1
      List1.additem (screen.fonts(I))
Next


To change mouse pointer to a custom mouse pointer, enter:

Screen.mouseicon  = LoadPicture(“arrow.ico”);
Screen.mousepointer = vbCustom

To center the form on the screen, enter the following code in FORM_LOAD event:

Private Sub Form_Load()
Dim x as integer, y as integer

   x = (Screen.Width - Me.Width) / 2
   y = (Screen.Height - Me.Height) / 2
   Me.Move x, y
End Sub

Printer Object
Printer object allows you to print to default printer. The following are the important properties of Printer object.

Property

Meaning

Copies
Specifies the number of copies to be printed. Default is 1.
ColorMode
Determines whether a color printer prints output in color or monochrome. Valid options are: 1 – monochrome, 2 – color. If the printer is monochrome then it ignores this property.
Devicename
Returns the name of the device.
Drivername
Returns the name of the driver
Orientation
Indicates whether documents are printed in portrait or landscape mode.
1 – portrait, 2 – landscape.
Page
Returns the current page number.
PaperSize
Returns or sets a value indicating the paper size for the current printer Please see on-line help for valid options.
PaperBin
Indicates the bin on the printer from which paper is fed when printing. Please see on-line help for valid options.
Printquality
Returns or sets a value indicating the printer resolution. Valid options are:
-1 Draft, -2 Low, -3 Medium, -4 High. 
You can also set this property to dots per inch (DPI), like 300.
Zoom
Returns or sets the percentage by which printed output is to be scaled up or down. Default is 0, which means normal size.
Table 11.3: Properties that are unique to Printer Object

Printer object also has collection of methods. While properties are used to change the settings, methods are used to actually print and control printing operations.

Following are the methods that are specific to Printer object. Remember Printer object has some of the common methods such as Circle, Line etc. But in this section, I will discuss about only the methods that are specific to Printer object. For complete list, please see on-line help.

Method

What it does?

EndDoc
Terminates a print operation sent to the printer using Printer object and releases the document to the print device or spooler. Printing will not start unless you execute EndDoc.
KillDoc
Terminates the current print job immediately.
NewPage
Ends the current pages and advances to the next page.
Print
Prints the given text to printer.
Table 11.4: Methods that are specific to Printer object.

The following are various examples regarding how to use Printer object properties and methods.

To display two lines in draft resolution mode, enter:

Printer.PrintQuality = -1  'draft resolution
Printer.Print "Who is the author of this book?"
Printer.Print "P.Srikanth"
Printer.EndDoc

To display two lines in two different pages with various other setting, enter:

Printer.CurrentX = 0
Printer.CurrentY = 0
Printer.colromode = 2  ' put in color mode
Printer.Orientation = 2 ' landscape
Printer.Zoom = 100       ' double the size
Printer.Print "This is at the uppper-left corner"
Printer.NewPage        ' go to next page
Printer.Print "This is in the second page"
Printer.EndDoc

App object
App object contains important information regarding the current application such as  help file to be used, whether previous instance of this application is running etc.

The following are the important properties of App object. For the complete list of properties, please see on-line help for App object.

Property

Meaning

ExeName
Returns the root name of the executable file (without the extension) that is currently running. If running in the development environment, returns the name of the project
Taskvisible
Returns or sets a value that determines if the application appears in the Windows task list.
HInstance
Returns a handle to the instance of the application. If project is run in IDE, returns the handle of the IDE.
LogMode
Specifies how logging  is to be carried out.
LogPath
Specifies the path and file name to which logging information should be written.
UnAttendedApp
Returns a value that determines if an application will run without any user interface.
Helpfile
Specifies the path and filename of a Help file used by your application to display Help or online documentation.
PrevInstance
Returns a value indicating whether a previous instance of the application is already running.
Startmode
Returns or sets a value that determines whether an application starts as a stand-alone project or as an ActiveX component.
0 – Standalone, 1 - ActiveX component.
Table 11.5:  Properties of App object.

The following are the available methods of App object.

Method

What it does?

Logevent logbuffer, eventtype
Logs an event in the application's log target, which is specified using LogPath property.
Logbuffer is the message to be logged.
EventType is: 1-error, 2-warning, 4 – information.
StartLogging logTarget, logMode
Sets the log target and log mode of an operation.
Table 11.6:Methods of App object.

To test whether application has started as a standalone or as an ActiveX component:

If App.StartMode = 0 then
   ‘do what you want for    standalone application
Else
    'do what you want for ActiveX component
End if

To prevent second instance from starting:

If not IsNull (App.PrevInstance) then
     Unload me
End if
 
Debug Object
Allows you to write to immediate window. This object is meaningful only when project is run in development environment. At run time Debug object is ignored.

The following are the methods available in Debug object.

Method

What it does?

Print
Prints the given text to Immediate window.
Assert
Suspends the execution at the line where method appears if the given condition is false. If the condition is true, it has no effect on execution.
Table 11.7: Methods of Debug object.

To suspend the execution of program if the value of variable amount is more than 10000, enter:

Debug.Assert amount > 10000

To print the value of variable amount to immediate window, enter:

Debug.Print  amount
Note: you can suspend execution of the program using stop method by pressing Ctrl + Break in VB IDE

Clipboard Object
Allows you to access system clipboard. Visual Basic applications can place data on to clipboard so that other applications can receive the data. In the same way it is also possible to receive data that is currently  placed on clipboard. The following are the available methods in clipboard.

Method

What it does?

Settext
Places the given text on the clipboard.
Setdata 
Places the given binary data, such as pictures, on the clipboard.
Gettext
Returns the text that is currently on clipboard.
Getdata
Returns the data that is currently on clipboard. This is used to retrieve binary data such as pictures.
Clear
Clears data that is on clipboard.
Getformat
Returns true if clipboard contains the data of the specified format. Please see on-line help for the list of valid formats.
Table 11.8: methods of Clipboard object.

Sample Application
It is time to consolidate. Let us develop an application that can place data on the clipboard or send the data to printer. The sample application displays the list of available fonts so that user can format the text before printing.  The application also takes care of enabling and disabling options such as cut and paste automatically.

user-interface of the application the following is the menu structure and what each menu item does.

Option

What it does?

Cut
Places the text that is currently selected in text box to clipboard. And removes the selected text from textbox.
Copy
Places the text that is currently selected in textbox to clipboard.
Paste
Copies the text that is currently available in clipboard at the cursor position in textbox. If any text is selected in text box then the text from clipboard replaces the selected text of the textbox.
Table 11.9: Meaning of options in Edit menu.
Let us now understand what these controls on the form do?

Text Box

Allows user to enter the text that can be sent either to clipboard or to printer. It supports multiple lines and also contains scrollbars.
First Combobox
Display the list of fonts available from Screen object. Initially it is set to font “Arial”. Whenever user selects a new font, the text in textbox will be displayed in the new font.

Second Combobox

Allows you to select a size for font. It displays number in the range 6 to 50 with an increment of 2. User is allowed to either select a number from the list. User is also allowed to enter a new value. The text in the textbox will be displayed in the new size.

Print command button

Prints the text that is in textbox in the selected font and with the selected size to default printer.  It uses Printer object to send text to printer.

Creating the sample application
The following are the steps to be taken to develop the sample application.

1.       Create a new project using File-> New Project and select Standard Exe as the type of the project.
2.       Place the required control
3.       Change the properties as shown in the table below.

Object
Property

Value

Form
Caption
System Objects Demo
Label1
Caption
Print Text
Text1
Name
Txtsample

Multiline
True

Scrollbars
3 –both

Text
“ “ ( Null string)
Combo1
Name
Cmbfonts

Style
2-dropdown list
Combo2
Name
Cmbsize
Command1
Name
Cmdprint

Caption
&Print
Command2
Name
CmdQuit

Caption
&Quit

Write code for Form_Load event to add the names of the available fonts using Screen object. Also add numbers in the range 6 to 50 with an increment of 2.


Private Sub Form_Load()
  'Load fonts from Screen objects
  For i = 0 To Screen.FontCount - 1
     Cmbfonts.AddItem Screen.Fonts(i)
  Next
  Cmbfonts.Text = "Arial"    ‘ select Arial as the default font
  'add numbers with increment of 2 to cmbsize
  For i = 6 To 50 Step 2
    cmbsize.AddItem i
  Next
  ‘select 6 as the default size
  cmbsize.ListIndex = 0
End Sub
Listing 11.1: Code for Load event of the form object.

Now let us write code to change the name of the font whenever user selects a new font name in ComboBox.

Private Sub Cmbfonts_Click()
  txtsample.Font.Name = Cmbfonts.Text
End Sub
Listing 11.2: Code for Click event of cmbFonts combo box.

Text property contains the name of the font currently selected. Use Name attribute of Font object to change the name of the font for textbox.

In the same way let us write code to change size of the font whenever user selects a different size using size Combobox. But as this is a dropdown combo box, user can also directly enter text into it. So after user enters the size, the new size should be used to change the size of text in textbox. For this we use LostFocus event of the Combobox. LostFocus event occurs when user is moving out of the Combobox.

So we have to write code for two events of size Combobox. Listing 11.3 shows the code for size combo box (cmbsize).

Private Sub cmbsize_Click()
 txtsample.Font.Size = Val(cmbsize.Text)
End Sub
Private Sub cmbsize_LostFocus()
 txtsample.Font.Size = Val(cmbsize.Text)
End Sub
Listing 11.3: Code for Size ComboBox.

Whenever user clicks on Print command button, the text that is entered by the user in the textbox should be printed using the selected font name and font size. The code in listing 11.4, accomplishes that task.
Private Sub cmdprint_Click()
   ‘ Change font name and font size of the printer object so that
   ‘ text that is printed is printed with those attributes
   Printer.Font.Name = Cmbfonts.Text
   Printer.Font.Size = Val(cmbsize.Text)
   Printer.Print txtsample     ‘ send text to printer
   Printer.EndDoc              ‘ indicate end of printing job
End Sub
Listing 11.4: Code for Print command button
Let us also complete code for quit buttons.

Private Sub cmdquit_Click()
  Unload Me
End Sub
Listing 11.5: Code for Quit button.

At this stage run the project and test whether changing font name in Combobox is changing the font of the text in textbox. Also test whether changing size is changing the size of character in textbox. Also test whether typing size in size Combobox and moving out of it is changing the size of the character.

If all tests are successful then proceed to next section, otherwise find out the bug and debug it. Remember, nobody is a born programmer. Programming is learnt by writing programs. Initially your program may not be successful. But finding out errors and correcting them is all what programming is all about. So do it.

Writing code for Edit menu
Now let us turn our attention to Edit menu. Options in Edit menu are used to place text in clipboard and retrieve text from clipboard.

First let us concentrate on Cut option. When user selects Cut option, the following steps are to be taken.

¨         Place the selected text of the textbox on Clipboard
¨         Delete the text that is selected.

We use SelText property of the textbox. SelText property of the textbox contains the text that is currently selected (highlighted).
Note: If no text is selected then SelText refers to current position in the textbox.

Here is the code for Cut option of edit menu.

Private Sub mnucut_Click()

'copy the selected text on to clipboard
Clipboard.SetText txtsample.SelText
'cut the selected text
txtsample.SelText = ""

End Sub
Listing  11.6: Code for Cut option.

Copy option also does the same as Cut option except that it doesn’t delete the selected text. Here is the code for copy option.

Private Sub mnucopy_Click()
 'copy the selected text on to clipboard
 Clipboard.SetText txtsample.SelText
End Sub
Listing 11.7: Code for Copy option.
Paste option takes the text that is in the clipboard and places it either at the current position, if nothing is selected, or replaces the selected text. Both the purposes can be served using SelText property of textbox. Listing 11.8, shows the code for Paste option.

Private Sub mnupaste_Click()
   ‘ get text from clipboard and replace selected text
   ‘ or place it at the cursor position if not text is selected
   txtsample.SelText = Clipboard.GetText
 
End Sub
Listing 11.8: Code for Paste option.

The next and last step is automatically enabling and disabling options in Edit menu depending upon the context. That means if no text is selected then Cut and Copy options are to be disabled. In the same way if no text is existing in clipboard then Paste option is to be disabled.

That means Cut and Copy are enabled only when text is selected in textbox.

Paste option is enabled only when clipboard contains text.

The following is the code for click event of Edit menu. Click event of Edit menu is the place where you have to enable or disable because, click event occurs before menu is displayed to user.

Note: But you cannot select click event of Edit menu in design mode like you can select for options. Because whenever you click on edit menu the options will be displayed but code window is not invoked. So get into code window and then select mnuEdit as the object and Click as the event and write the following code.

Private Sub mnuedit_Click()
  
' disable all options
mnucut.Enabled = False
mnucopy.Enabled = False
mnupaste.Enabled = False

If txtsample.SelText <> "" Then
    ' enable cut and copy options
    mnucut.Enabled = True
    mnucopy.Enabled = True
End If

‘ check whether clipboard has any text

 If Clipboard.GetFormat(vbCFText) Then
     mnupaste.Enabled = True
 End If

End Sub
Listing 11.9: Code for Edit menu.

GetFormat method of Clipboard object returns true if data in the clipboard is of the specified type. Here we are checking whether clipboard has any text, using  vbCFText constant. For the list of available constants and corresponding numeric values, please see on-line help for GetFormat method of Clipboard object.

System objects are useful in Visual Basic. They are used to access system devices. App does not refer to any device but it contains information regarding application.