Capturing Webcam using Visual Basic

November 10, 2006 Visual Basic, Visual Studio ,

While I write this article, I am referring to a real-time system that captures the images when needed through a web cam, placed in one corners of the library.  The need of the hour was to keep a central monitoring system so that the librarian could have a sight over the people in the library and their behavior.


And while I was designing this system, the first important step was to activate a webcam through my software that could show the frames capture the images when needed.  These images could be stored on the hard disk and viewed through and picture editor.  The user should have the facility to save the image in any of the three universal image formats i.e. Bitmap, GIF and JPG.  After development phase of the same, the goal was to have automatic capturing of the images and storing it with file name of the format:




The desired frequency of capturing an image was once in every 5 minutes.  Thus in a day having 24 hours having 1440 minutes, 288 pictures can be captured. So the numbering could follow a pattern from 0000 to 0287 having filename pb0000.jpg to pb0287.jpg


In this article, I am presenting a part of my software which concerns capturing a picture from webcam when the user intends to do the same.  I leave the further programming part to the user which is application dependent.


Using Dynamic Link Libraries


Visual Basic can communicate directly to Windows Application Programming Interface (API) which are defined in dynamic link libraries (abbreviated as DLL’s) that are stored in \windows\system directory. 


Some of the core DLL files Windows supports are listed in the table 1.


Table 1: DLL supported by Windows


Sr. No


Applications it supports



User Interface Routines






Security & Registry Calls



Graphics Device Interface



32-bit Windows applications



32-bit Shell applications


However we need not remember the DLL and their function because they are directly being called by API.  The functions of API can be viewed using API Viewer (a tool provided in Microsoft Visual Studio Package) and is shown in Figure 1.


Figure 1: API Viewer – Win32api.txt




Let’s see the Item : SendMessage which we shall in our program.


The SendMessage is defined in API as under:


Public Declare Function SendMessage Lib “user32” Alias “SendMessageA” (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long


Let’s understand the syntax of this function.


Function Name:                           SendMessage

Actual Windows Function Name:     SendMessageA

DLL:                                          user32

Arguments & their types:

hwnd            handle                    Handle of the Window

wMsg            unsigned int             Message to be sent

wParam        unsigned int             Message-specific information

lParam          long                       Message-specific information


The other API reference that we shall use is defined in AVICAP32.DLL and is called as capCreateCaptureWindow.  The function call is as under:


Public Declare Function capCreateCaptureWindow Lib “avicap32.dll” Alias “capCreateCaptureWindowA” (ByVal lpszWindowName As String, ByVal dwStyle As Long, ByVal X As Long, ByVal Y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hwndParent As Long, ByVal nID As Long) As Long


Public mCapHwnd As Long


Now let’s see the core programming of webcam using these API calls.

Designing Form & Coding


The form designed can be considered to have following elements:



Number of objects


Picture Box






Common Dialog



Command Buttons






However to provide alignment, we can introduce frames or picture boxes.  I have kept two additional picture boxes; one of it has the command buttons, the other one has the common dialog.


We can avoid the Start button that is used to initialize web cam and start the webcam as soon as the form is loaded.  Similarly Stop button can also be omitted as the picture can also be captured and saved by Save As button.  Initially, Stop button is kept disabled.


This Save As option can be later modified to capture images at a regular interval without requiring user interface and in that case, we can keep the form as small as an Exit button (the picture box can be kept invisible too!)  The timer is used to refresh webcam images.


Let us not analyze the code.


Private Sub cmdStart_Click()

mCapHwnd = capCreateCaptureWindow(“WebcamCap”, 0, 0, 0, 320, 240, Me.hWnd, 0) ‘Get hWnd for webcam so we can use it

DoEvents: SendMessage mCapHwnd, 1034, 0, 0
                   ‘Capture from webcam

tmrMain.Enabled = True ‘Enable timer to refresh webcam images

cmdStop.Enabled = True ‘Make stop button enabled

End Sub


The first statement calls a API function and as per the syntax mentioned before,


WebcamCap is the window name, the first ‘0’ corresponds to the style, second and the third ‘0’ indicate x and y co-ordinates of capturing window, 320 is the width of capture window and 240 is the height, me.hwnd is the handle of the current window and the last ‘0’ is the Window Identifier.


The style of the window can be set by CreateWindowEx(). The function capCreateCaptureWindow returns a handle of the capture window if successful or NULL otherwise.


We then send a specific message to a window.  This message code is 1034.  By the number 1034, the computer interprets connection of webcam.


The similar concept is used to stop the webcam.  The code will appear as:


Private Sub cmdStop_Click()

tmrMain.Enabled = False ‘Disable refreshing of webcam images

DoEvents: SendMessage mCapHwnd, 1035, 0, 0
                   ‘Stop capturing of images from webcam

cmdStart.Enabled = True ‘Make start enabled

cmdStop.Enabled = False

End Sub


We have used a common dialog control through which we can save the image file when clicked on Save As.  So, the code for saving the image will be:


Private Sub cmdSaveAs_Click()

CommonDialog.Filter = “Jpeg (*.JPEG)|*.JPG”

‘Supported file-type is JPG since it is compressed format


‘Show save dialog

SavePicture picCapture.Image, CommonDialog.FileName  

‘Save picture on any drive configured on PC

‘this also includes established LAN drives

End Sub


The first line of the code for saving is used to define the default type of file that can the user can give.  However, if the user wishes to save it by some other extension, he needs to type the same.


Some applications require capturing the images and copying it to clipboard.  To do this job, we need to first capture the frame where the image is being displayed and then copy it to clipboard.  This two stage procedure can be summed up as:


Private Sub cmdCopy_Click()

SendMessage mCapHwnd, 1084, 0, 0

‘Capture frame from webcam

DoEvents: SendMessage mCapHwnd, 1054, 0, 0

          ‘Stop capturing of images from webcam

End Sub


The programmer needs to take care that the co-ordinates of the frame are defined correctly. It should remain the same through-out the program and hence it is advisable to define these constants globally.  Here 1084 is the code for getting the frame and 1054 for copying the image.


The most important part which is refreshing the images captured by webcam so that it appears as if the stream is being captured continuously. This can be done by the use of timer tmrMain.


Private Sub tmrMain_Timer()

On Error Resume Next


picCapture.Picture = Clipboard.GetData

‘Paste captured frame from clipboard

End Sub


The algorithm for saving the file automatically can be implemented in this format.  The interval of timer (in milliseconds) needs to be set when the form starts. 


Dim counter As Integer

SavePicture picCapture.Image, “c:\lbsystems\images\date” & Counter & “.jpg”

Counter = Counter + 1


With this, one can easily capture any stream of data from webcam but when the form is unloaded or when the program is ended, the webcam is still in the process of connection.  This should be terminated so that memory as well the processor is freed.


Private Sub cmdExit_Click()

DoEvents: SendMessage mCapHwnd, 1035, 0, 0  ‘Stop webcam capturing

Unload Me

End Sub


When an interrupted termination occurs, this program will again not be able to free the memory.  So a piece of code needs to be written in Form_Unload


Private Sub Form_Unload(Cancel As Integer)

DoEvents: SendMessage mCapHwnd, 1035 , 0, 0

          ‘Stop webcam capturing

End Sub

With that, one module of capturing webcam is all set to be implemented in any project.  I hope this article has given you information to start off with any project at beginner’s level.

This article was first published in DeveloperIQ


Visual Basic – Application Design and Development

July 10, 2006 Visual Basic, Visual Studio ,

In this article, we shall focus something other than what we have covered in our previous articles.  We shall not deal with Database Management though it is important part of application designing.


We have various definitions for an application but we believe it to be a software package that satisfies the needs of the end user.   To design such a project, a project leader needs to consider designing and analysis part. Along with designing the project, one needs to think of user-friendliness of the application. 


Application Design


We would suggest you use Microsoft Project for designing the project and managing it.  Divide the project with differ rent modules and decide the time guidelines for completing those modules.  We’ll take one of our applications as an example, Clinical Management System. 


The system had following modules:


  1. Doctor Specific: Entry of the details of Different Doctors, their available times, searching for their records, Appointments.
  2. Patient Specific: New/Old Case, Patient Entry, Diagnosis, Printing
  3. Inventory Specific: Expenses, Returns, Balance Sheets
  4. Program Specific: Users & Passwords, Birthday Reminders, Emails
  5. Database Specific: Backup, Restore Facilities.

Decision Trees


In each of the projects, there are various phases/modules that require taking detailed analysis of the possible options with the data, data flow and data security.  It is important to analyze all the possible alternatives and find appropriate solution to it. For above project, following decision trees need to be analyzed.



Decision Trees

Doctor Specific

While entry of doctor, one needs to check whether the Details of the doctor are pre-entered or not.  If the doctor is available, the appointment can be given to the patient.

Patient Specific

To check whether the case is old one or new.  If it is a new case, enter the details of patient along with photograph. While diagnosis, the doctor enters the symptoms and the software finds out the prescriptions for same combination.  If no records are found, we are required to add a new prescription at the very instant of diagnosis.

Program Specific

Check validity of users and check the password authenticity.  It needs to send birthday mails to patients whose birthday is on the current day automatically.


When these conditions are met, what action the software should take and when conditions other than those defined, one needs to provide proper algorithm. We prefer to prepare decision trees as per the modules.  You can choose any other method, which suites you.


After proper analysis of the problem, we need to design the application, which is described in the next topic.

Analysis to Design Transition


Analysis to Design Transition involves


·         Identification of Requirements

When the requirements are to be considered, one needs to understand different types of requirements such as System Requirements, Memory Requirements and Cost Factors.  But at the programming aspects, the programmer needs to think of various issues like security of data, security from piracy, effect of malicious code on the application data and speed of operation.

·         Design Standards.

While programming one needs to understand the need of uniformity of code, which is also a part of designing.  One should adhere to naming conventions and should provide commenting so as to have readability.

Design, if considered to be one that appears on screen, should be simple and decent.  Tips regarding where to enter data and its format should be provided where necessary.

Strategic Testing


Each and every module should be first tested thoroughly before giving it to the customer.  The programmer should test the complete project on Three-Value System.  As per the Three-Value System, the data should be entered in three different modes like Low value, Medium Value and High Value. 


Third party software are also available for testing purposes.  It’s advisable to use this software only when you’re selling your product at a good price because these third-party software are costly. 


User Friendly



User Friendly means involves

·         Onscreen Help

There are three ways to help a user while he is doing data entry.

  1. Provide him with a single line help at bottom of screen which we call tip
    (Use a StatusBar).
  2. Help him by a help box at an un-occupied part of screen.
    (Use frames with different background color for this)
  3. Provide him a help when he presses F1.
    (Use Microsoft Help Workshop for creating help)


·         No maintenance

These days maintenance is one of the biggest issues.  Maintenance also includes updating the software without any paying additional costs. Effects of virus attacks should also be considered.

Creating Application


After we have created our application, it’s the time to make the setup file.  To create a setup file, we use Package and Deployment Wizard that is bundled with Microsoft Visual Studio as shown in Figure 1.


We browse the project and then click on Package to proceed ahead.  The wizard will then search the dependencies of the application.


When we intend to make an executable setup.exe, we select Standard Setup Package  as seen in Figure 2. Another case is Dependency File which is used to create a file listing information about the run-time components required by your application.


Select the folder in which we would like to store the package (see Figure 3).  Include the drivers which are intended to be included in the application.








Figure 1: Package and Deployment Wizard




Figure 2: Packaging Type




Figure 3: Selecting Package Folder


Many of the applications require databases and other text files, which need to accompany the application such as .hlp, .mdb, .htm, .txt etc (See Figure 4). 




Figure 4: Addition of Files

In the next step, we decide the distribution type of the application.  We can distribute the application in a single cab or in multiple cabs.  If we select deployment with multiple disks, we can specify the capacity of disk from 360K to 2.88MB.




Figure 5:  Cab Options


The last stage is to add Installation Title to the application. In our example, we have used Clinical Management System. (See Figure 6)


In Windows, we group the application in Programs Menu.  The group in which the application can be listed and the items under that group can be decided as shown in Figure 7.



Figure 6: Installation Title Screen




Figure 7: Icons


Some of the files may be used by several applications and will be un-installable only if all the Applications using them are uninstalled. These files are shared files. It is better to include OCX and DLL files as shared files. (See Figure 8).




Figure 8: Shared Files


We then click on Finish to complete this package and make a SETUP.EXE. This setup file can be loaded on disk and distributed.


Note: This series was first published in DeveloperIQ and was co-authored by Punit Ganshani with Pranjali Bakeri in 2005-2006.


Visual Basic – Registry Programming

June 1, 2006 Visual Basic, Visual Studio ,

One of the most required tasks these days for software is to remember the configuration and the settings as changed by the user and function accordingly. This can be done either by keeping a separate database for such parameters or by using Windows Registry.  In this article, we shall deal with Registry Programming

Registry Programming

What is Registry?

The Registry is a database used to store settings and options for the 32 bit versions of Microsoft Windows including Windows 95, 98, ME and NT/2000. It contains information and settings for all the hardware, software, users, and preferences of the PC.


Any changes in software configuration or changes done in Control Panel settings are reflected and stored in the Registry.

Structure of Registry


The Registry has a hierarchal structure and appears similar directory structure as seen in Windows Explorer.  We can open Registry Editor by typing regedit in Start Menuà Run




Figure 1: Registry Editor

Each main branch (win a folder icon) is called a Hive, and Hives contains Keys. Each key can contain other keys (as sub-keys), as well as Values. The values contain the actual information stored in the Registry. There are three types of values; String, Binary, and DWORD – the use of these depends upon the context.


Before starting registry programming, let’s first understand what each of the Hives mean and the values that can stored in sub-keys.


Table 1: Hives




Data Stored


File Association

The branch contains all of your file association mappings to support the drag-and-drop feature, OLE information and Windows shortcuts.


Information regarding User Logged on.

The branch links to the section of HKEY_USERS appropriate for the user currently logged onto the PC and contains information such as logon names, desktop settings, and Start menu settings.


Hardware Specific Information

This branch contains computer specific information about the type of hardware, software, and other preferences on a given PC.


User Information

This branch contains individual preferences for each user of the computer, each user is represented by a SID sub-key located under the main branch.


Current Hardware Configuration

This branch links to the section of HKEY_LOCAL_MACHINE appropriate for the current hardware configuration.


Plug-&-Play Features of Windows

This branch is for use with the Plug-&-Play features of Windows, this section is dymanic and will change as devices are added and removed from the system



Values are of four types varying on the type of data we wish to store in the registry.


Table 2:  Types of Values





This type stores the value as raw binary data.


This type represents the data by a four byte number and is commonly used for Boolean values, such as “0” is disabled and “1” is enabled.


This type is an expandable data string that is string containing a variable to be replaced when called by an application.


This type is a multiple string used to represent values that contain lists or multiple values, each entry is separated by a NULL character.


This type is a standard string, used to represent human readable text values.


Saving Values in Registry


When we install our software, say for example, Numerology Report System, a hive is automatically created in Registry as shown in Figure 2.





Figure 2: Registry Key in Registry Editor


We create an object as registry by


Dim reg As cRegistry


Thereafter, we enter the values in the keys by a small snippet.


Set reg = New cRegistry

      ‘This will create a new section to store your own keys in

reg.Classkey = Hkey ‘HKEY_CURRENT_USER

reg.SectionKey = SectionKey   ‘Software\Numerology Report System

‘create the above key

reg.CreateKey                 ‘My Settings

reg.Valuetype = Valuetype     ‘REG_sz

reg.Valuekey = Valuekey       ‘Date

reg.Value = Value             ‘Date$


Getting Values from Registry


Let us obtain the value of the key, which is created while installation of our software.





Figure 3: Value of the Key in Registry Editor


We can obtain this value using same method:


Set reg = New cRegistry

reg.Classkey = Hkey

reg.SectionKey = Section

reg.Valuekey = Valuekey


Let’s write a piece of code to write in registry and read it.


Dim reg As cRegistry


Private Function CreateKeys(HKey As String, SectionKey As String, ValueKey As String, Valuetype As String, Value As String)

      Set reg = New cRegistry

       ‘This will create a new section to store your own keys in

reg.Classkey = Hkey

reg.SectionKey = SectionKey

‘create the above key


‘Save the Form settings to the registry

reg.Valuetype = Valuetype

reg.Valuekey = Valuekey

reg.Value = Value

End Function



‘SectionKey = Software\VB and VBA Program Settings\Numerology Report System\My Settings

‘ValueKey = Date

‘ValueType = Reg_sz

‘Value = 01-05-2006


Call CreateKeys(HKEY_CURRENT_USER, “Software\VB and VBA Program Settings\Numerology Report System\My Settings

“, “Date”, Reg_sz, date$)



‘Section = “Software\VB and VBA Program Settings\Numerology Report    System\My Settings

‘ValueKey = Date


Private Function GetKeys(Hkey As String, Section As String, Valuekey As String)  ‘Reads the Registry

    Set reg = New cRegistry

    reg.Classkey = Hkey

    reg.SectionKey = Section

    reg.Valuekey = Valuekey

End Function


Call GetKeys(“Software\VB and VBA Program Settings\Numerology Report System\My Settings”, “Date”)


Another way to save and get values of a key in registry


There’s one method to save keys and get their values through coding.  This method uses statements instead of creating objects. They are listed in Table 3.


Table 3: Setting and Getting Values



Setting a Value

Getting Value


SaveSetting(appname, section, key, setting)

GetSetting(appname, section, key)


SaveSetting App.Title, “Settings”, “Left”, Me.Left

Me.Left= GetSetting(App.Title, “Settings”, “Left”)


The key Settings is created under the key which is made during installation procedure and if we wish to have different path (say for example HKEY_CURRENT_USER\SOFTWARE\NRS) then we need to mention in


SaveSetting App.Title, “HKEY_CURRENT_USER\SOFTWARE\NRS“, “Left”, Me.Left


Let’s now delete the key we have made.

Deleting Registry Keys


The statement for deleting the registry settings, we use the DeleteSetting statement as shown below,


DeleteSetting appname, section[, key]    


Let’s understand the syntax of this statement.


Table 4: Syntax of DeleteString





Application Name
(normally referred as App.Title or App.EXEName


Name of the Section where the key is stored/key which needs to be deleted.


Expression containing name of the key setting being deleted.


DeleteSetting App.Title, “Settings”


To check if the key is deleted or not,


If len(GetSetting(App.Title, “Settings”, “Left”)) = 0 
‘then it doesn’t exists

      MsgBox “Key not found”

End If



Why use Registry


The question that remains unanswered is why use registry?  Registry can be used for several reasons as listed below


·         To remember the last used configuration of software.

·         To keep a track of when all the software was used.

·         To keep license keys.

·         To track the changes made by the software in the system.


With this we end this article on Registry Programming.

Note: This series was first published in DeveloperIQ and was co-authored by Punit Ganshani with Pranjali Bakeri in 2005-2006.


Visual Basic – Multimedia Programming

May 20, 2006 Visual Basic, Visual Studio ,

Multimedia Programming can be done in two ways; using Multimedia Control or by using various API’s.  We shall concentrate more on using Multimedia Control in this article so that we can do justice with it.  Brief information about implementing through API is given at the end of the article.


Microsoft Multimedia Control


There are various controls that help us implement Multimedia Programming in Visual Basic.  Some of them which we shall cover here are

·         Microsoft Multimedia Control and

·         Windows Media Player


To add these controls in our application, select them from Project à Components.   Let us explore the Microsoft Multimedia Control which appears as shown in Figure 1.  We can change the properties of this control as per the function that we wish to do through this control.




Figure 1: Microsoft Multimedia Control


The first task with this control is to select a device on which we need to operate.  This is controlled using DeviceType property of the control.  This property defines the multimedia type the control will support. The DeviceType property can accept various strings in Table 1.


Table 1: Strings for DeviceType


Strings for DeviceType

We can set this property dynamically through code by writing,




However, we need to open the device first and then use it.




Sometimes, Device automatically gets initiated and hence DeviceType definition is not required.




Digital Video







We shall understand the concept of Multimedia Control with this application developed by us.  This application supports WAV, MIDI, MP3, AVI and MPEG formats of Files. 




Figure 2: Multimedia Control Software


Initially we target at opening file from a desired type of files.

Dim strmode, song As String


Private Sub mnuOpen_Click()

CommonDialog1.Filter = “WAV Files (*.wav)|*.wav|” & “MP3 Files (*.mp3)|*.mp3|” & “Video Files (*.avi)|*.avi|” & “MIDI Files (*.mid)|*.mid|” & “MPEG Files (*.mpg)|*.mpg|”


song = CommonDialog1.FileName

MMControl1.TimeFormat = mciFormatMilliseconds

MMControl1.FileName = song

StatusBar1.Panels(2).Text = strmode

StatusBar1.Panels(4).Text = song

If UCase(Right$(CommonDialog1.FileName, 3)) = “AVI” or &      UCase(Right$(CommonDialog1.FileName, 3)) = “MPG” Then

    Me.Width = 13725

    Me.Height = 8565

    MMControl1.hWndDisplay = Picture1.hWnd


    Me.Width = 4425

    Me.Height = 5895

End If

MMControl1.Command = “Open”

End Sub


In the above piece of code we set the time format in MilliSeconds by using TimeFormat property. This property accepts other formats as mentioned in Table 2.

Table 2: TimeFormat Strings


TimeFormat String

Equivalent Code




Hours, Min and Seconds.  This data is combined to form a 4-byte integer in same order*



Minutes, Seconds, Frames

This data is combined to form a 4-byte integer in same order



Frames are stored to form a 4-byte integer.



24-frame SMPTE packed data in 4 byte variable in order of Hours, Minutes, Seconds and Frames



25-frame SMPTE packed data in 4 byte variable in order of Hours, Minutes, Seconds and Frames



30-frame SMPTE packed data in 4 byte variable in order of Hours, Minutes, Seconds and Frames



30Drop-frame SMPTE packed data in 4 byte variable in order of Hours, Minutes, Seconds and Frames



Bytes are stored in 4-byte integer variable



Samples are stored as 4-byte integer variable



Tracks, Minutes, Seconds and Frames are combined in 4-byte variable in same order.

*Here order means from Least Significant Byte(LSB) to Most Significant Byte(MSB)


The second part which is important is viewing of pictures in AVI or MPEG files.  This is done using handles of Picture Box.  We connect the Multimedia Control and Picture Box using hWnd Property of PictureBox and placing the handle in the Multimedia Control’s hWndDisplay property.


We leave an exercise to think over usage of Image Control instead of PictureBox.  Can you predict why we can not use an Image Control?  An Image control doesn’t have hWnd Property so that you can access the frames of the Picture being played by Multimedia Control.


Private Sub MMControl1_StatusUpdate()

Select Case MMControl1.Mode

    Case mciModeReady

        strmode = “Ready.”

    Case mciModeStop

        strmode = “Stopped.”

    Case mciModeSeek

        strmode = “Seeking.”

    Case mciModePlay

        strmode = “Playing.”

    Case mciModeRecord

        strmode = “Recording.”

    Case mciModePause

        strmode = “Paused.”

End Select

 lblLength.Caption = Str(MMControl1.Length / 10)

 lblPos.Caption = Str(MMControl1.Position / 10)

 StatusBar1.Panels(2).Text = strmode

 StatusBar1.Panels(4).Text = song

 ProgressBar1.Max = Val(lblLength.Caption)

 ProgressBar1.Value = Val(lblPos.Caption)

End Sub

When a song or movie is being played, the mode of Multimedia Control (MMControl1) keeps changing.  Various modes are checked in the above function and the status is updated in the StatusBar1.  The Length of the track is determined by Length property, while the current position of track is known by Position property.


After the song or movie is played, we need to check if there were any errors during execution.  To check this, we initially set the Notify property to True.  By this property, as soon as the song is completed the Done Function of Control is executed.


Private Form_Load()

MMControl1.Notify = True

End Sub


Private Sub MMControl1_Done(NotifyCode As Integer)

If MMControl1.Error <> 0 Then

      MsgBox MMControl1.ErrorMessage

End If

End Sub


To add few more facilities, we write a code that will enhance our application by using various tools like Next, Stop, Pause and so on…

Private Sub MMControl1_StopClick(Cancel As Integer)

MMControl1.Command = “Stop”

End Sub


Private Sub MMControl1_NextClick(Cancel As Integer)

MMControl1.Command = “Next”

End Sub


Private Sub MMControl1_PauseClick(Cancel As Integer)

MMControl1.Command = “Pause”

End Sub


Private Sub MMControl1_PlayClick(Cancel As Integer)

MMControl1.Command = “Play”

End Sub


Private Sub MMControl1_PrevClick(Cancel As Integer)

MMControl1.Command = “Previous”

End Sub


Let’s take an example where we wish to start the song after 2 minutes and till 10 minutes. For that we use Form and To property.  The calibration of time needs to be done according to the format of TimeFormat as shown in code below


Private Sub cmdPlay_Click()

MMControl1.TimeFormat = mciFormatMilliSeconds
MMControl1.From = 2    
‘Start Time

MMControl1.To = 10      ‘End Time

MMControl.Command = “Play”

End Sub


To move the Control Forward or Backward, we can use the Step and Back Multimedia Control Commands to step through animations frame by frame by the number of frames set in the Frames Property.  To check the availability of connection with the device, we use CanStep Property as shown below:


Private Sub cmdFWD_Click()
If MMControl1.CanStep Then
MMControl1.Frames = 1  
‘One Frame Ahead

MMControl1.Command = “Step”

End If

End Sub


Private Sub cmdBACK_Click()
If MMControl1.CanStep Then
MMControl1.Frames = 1  
‘One Frame Back

MMControl1.Command = “Back”

End If

End Sub


Windows Media Player


Let’s implement Multimedia Programming using Windows Media Player Control.  We first add the Control through Project Menu à Components à Windows Media Player.


We shall develop one more application program and understand the working of this control.  The application after designing shall appear as shown below.





Figure 3: Windows Media Player Control


The application aims at creation of playlist and playing files in that order.  The reader requires knowledge of File Management which we covered in the previous articles (December 2005 Issue).  The playlist is stored in a text file c:\Playlist.txt and if the file is not empty, the list is loaded in a list box.  So, when the application starts, the first target is to load Playlist.  In order to have status as global through out our program, we define few variables allowplay, paused and allowpause.


Dim allowplay As String

Dim paused, allowpause As Boolean


Private Sub Form_Load()

allowpause = False

Dir1.path = Drive1.Drive

paused = False

On Error Resume Next

If FileLen(“c:/PlayList.txt”) = 0 Then

    Open “c:/PlayList.txt” For Output As #1

    Close #1

End If


Open “c:/PlayList.txt” For Input As #1

Do Until EOF(1)

    Input #1, playlistitem

    lstSelectedEntries.AddItem playlistitem


Close #1

allowplay = “no”

End Sub


The Control MediaPlayer1 has an in-built function Pause.  When New Stream is loaded, AllowPause is made True.  This condition is checked here, and if this is satisfied it further checks if previously Pause button is pressed (by condition on variable paused).  If previously Pause was pressed, it means the user intends to play the Stream which is coded in second part of the function


Private Sub cmdPause_Click()

If allowpause = True Then

 On Error Resume Next

 ‘If pause was not pressed previously, Pause the song.

 If paused = False Then


  paused = True

  allowplay = “no”

  Exit Sub

 End If

 ‘If pause was previously pressed, Play the Song

 If paused = True Then


  paused = False

  allowplay = “yes”

 End If


End If

End Sub


Let’s understand the fundamental of Play Button.  When Play Button is pressed, it plays the songs only if either the song is in pause mode or a selected song is to be played. Suppose a song is being played or is in Pause Condition.  If in such a situation, user selects another song and presses Play Button then the newly selected song should be played.  This logic is implemented in the second half of the code written below:


Private Sub cmdPlay_Click()

If paused = True Then         ‘If previously paused, then Play


paused = False

allowplay = “yes”

Exit Sub

End If


If paused = False Then        ‘If previously Playing, then play the selected song, which may no always be the one currently played.


MediaPlayer1.Open txtSelected.Text

lblSec = “0”                  ‘The display timers are reset to 0:00

lblMin = “0”

lblSec2 = “0”

Exit Sub

End If

End Sub



Stop Button has a very simple logic. When Stop Button is pressed, MediaPlayer1 Control should stop the song, the displayed timers as well as the actual timer (controlled by allowplay variable) should be reset.


Private Sub cmdStop_Click()


allowplay = “no”

lblSec = “0”

lblMin = “0”

lblSec2 = “0”

allowpause = False

End Sub


The Timer Control used here has an interval of 1 second.   As time elapses, the same needs to be displayed on screen using 3 labels; one to display minute (assuming no song is greater than 9 minutes) and two for seconds.


Private Sub Timer1_Timer()

If allowplay = “yes” Then

 If lblSec = “9” Then

   lblSec = “0”

   lblSec2 = lblSec2 + 1

   If lblSec2 = “6” Then

        lblSec2 = “0”

         lblMin = lblMin + 1

    End If


   lblSec = lblSec + 1

  End If

End If

End Sub


What happens when a new stream is opened or a stream ends? Two functions are activated.  They are NewStream and EndOfStream.  These functions should first reset the timer.  The functions can be coded as shown:


Private Sub MediaPlayer1_NewStream()

lblSec = “0”

lblSec2 = “0”

lblMin = “0”

allowplay = “yes”

allowpause = True

End Sub



Private Sub MediaPlayer1_EndOfStream(ByVal Result As Long)

allowplay = “no”

lblSec = “0”

lblSec2 = “0”

lblMin = “0”

allowpause = False

End Sub


The application still appears to be raw as one needs to click on Import Button to transfer the file to Playlist and again Click on Play Button to play it.  We add some flexibility in our program.  A double click on a song in Playlist will play the song.


Private Sub lstSelectedEntries_Click()

txtSelected.Text = lstSelectedEntries.Text

End Sub


Private Sub lstSelectedEntries_DblClick()

txtSelected.Text = lstSelectedEntries.Text


lblSec = “0”

lblMin = “0”

lblSec2 = “0”

MediaPlayer1.Open txtSelected.Text

End Sub


Private Sub lstSelectedEntries_KeyPress(KeyAscii As Integer)

txtSelected.Text = lstSelectedEntries.Text

End Sub


And finally, our application is ready to use.


Multimedia Through API


We just covered the concepts of API in our previous article in this issue.  So we would just brief you with the API function and we leave the programming part to you because it is yet another simple way to do multimedia programming.


A song or music can be played using PlaySound function from winmm.dll.  The syntax of the function is


Public Declare Function PlaySound Lib “winmm.dll” Alias “PlaySoundA” (ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long


There’s something to observe in the above syntax.  The actual name of the function is PlaySoundA.  The difference is PlaySound and PlaySoundA is that the latter uses ANSI text strings. We are here just interested in knowing the values of dwFlags.


dwFlag Value



Play sound synchronously


Play sound asynchronously


If no sound is found, silence is not default


lpszName points to a memory file


Loop until next PlaySound


Don’t stop any currently playing sound


An example to use this function is


Private Sub cmdPlay_Click()

PlaySound(song, 0&, &H0)

End Sub


Note: This series was first published in DeveloperIQ and was co-authored by Punit Ganshani with Pranjali Bakeri in 2005-2006.

Visual Basic – Application Programming Interface

April 5, 2006 Visual Basic, Visual Studio ,

Dynamic Link Libraries


Windows has many in-built functions that we haven’t yet used and these functions are defined in libraries, which are called as Dynamic Link Libraries (DLL’s). These libraries are defined in \windows\system directory. And the pre-defined functions in DLL are called as Application Programming Interface (API).


Let’s have a look at commonly available DLLs


Table 1: DLL’s supported by Windows


Sr. No


Applications it supports



Security & Registry Calls



Common Dialog API Library



Graphics Device Interface



32-bit Windows applications



32-bit Compression Routines



Multiple Provider Router



32-bit Shell applications



User Interface Routines



Version Library



Multimedia Programming


Windows makes our task a bit easier by not letting us remember the names of DLL’s.  These DLL’s are directly called by API.  So, we need to understand how to use the functions of API.  Before we proceed to use of API functions, let’s first have a look to how to view the functions in API through API Viewer (a tool provided with Microsoft Visual Studio.)




Figure 1: API Viewer – Win32api.txt


Let’s see the item: SetCapture in order to understand the structure of an API call.


Public Declare Function SetCapture Lib “user32” Alias “SetCapture” (ByVal hwnd As Long) As Long


Let’s understand the syntax of the function:


Table 2: Syntax of SetCapture


Function Name


Actual Windows Function Name

SetCapture (written after Alias)





Handle of the Window

Creating Device Context

What is Device Context


A device context is a Windows data structure containing information about the drawing attributes of a device such as a display or a printer. All drawing calls are made through a device-context object, which encapsulates the Windows APIs for drawing lines, shapes, and text. Device contexts allow device-independent drawing in Windows. Device contexts can be used to draw to the screen, to the printer, or to a metafile.


Device Context and API Calls


Each of the Visual Basic Controls has an hDC property, which holds their device context.  We can also get a device context for a window using GetDC, which on success returns handle to device context and on unsuccessful attempt, returns zero.  Similarly, to create a device context for a device, we can use CreateDC function.


Public Declare Function GetDC Lib “user32” Alias “GetDC” (ByVal hwnd As Long) As Long


Public Declare Function CreateDC Lib “gdi32” Alias “CreateDCA” (ByVal lpDriverName As String, ByVal lpDeviceName As String, ByVal lpOutput As String, lpInitData As DEVMODE) As Long


Let’s first understand the arguments of both of these.


Table 3: Arguments of CreateDC





This string specifies the filename of the device driver.
No extension is specified.


Name of specific device to be supported.


Output file or Device Name.


This string defines device-specific configuration.

This parameter is null to use default Initialization, else required configuration is provided.


We shall not be using Device Context in our application but one should have its knowledge while programming graphics.

Capturing Mouse Motion on Screen

Defining Application Problem


In this application, our focus is to capture the motion of the mouse.  On pressing the Record Button, the motion tracking starts and this stops on pressing Stop Button.  We can view the motion by pressing Play Button.

Understanding API


Let’s quickly review the different API functions we shall use in our screen capture program.  The Syntax and their function is written in Table 4.


Table 4: API’s used in application



API Function





Private Declare Function GetCursorPos Lib “user32” (lpPoint As POINTAPI) As Long


Retrieves the cursor’s position, in screen coordinates.


Private Declare Function SetCursorPos Lib “user32” (ByVal X As Long, ByVal Y As Long) As Long


Moves the cursor to the specified screen coordinates.



Private Declare Sub Sleep Lib “kernel32” (ByVal dwMilliseconds As Long)

The Sleep function suspends the execution of the current thread for at least the specified interval.



Here, POINTAPI needs to defined as,


Private Type POINTAPI

        X As Long

        Y As Long

End Type

Application Design


In this application, we use following tools:


Table 5: Controls Used in Application



No Of Times Used


Command Buttons















The crux of the program lies in programming the timer.


Private I As Long

Private sMouseArray() As String


Private Function RecordMouse() As String

Dim mouse As POINTAPI

GetCursorPos mouse

RecordMouse = mouse.X & ” ” & mouse.Y

End Function


Private Sub tmrMouse_Timer()

ReDim Preserve sMouseArray(I)

sMouseArray(I) = RecordMouse

I = I + 1

End Sub


In the above code, RecordMouse is a function in which the current position of mouse is obtained.  RecordMouse is called in 2nd line of tmrMouse.  In this function, the current position of mouse is stored in sMouseArray. sMouseArray  and I are global variables.


The second important part of the application is to Play the motion of the mouse from the sMouseArray.

Private Sub cmdPlay_Click()

Dim J, lPlay, lX, lY As Long

Dim sSplit() As String

lPlay = I

For J = 1 To lPlay

    sSplit = Split(sMouseArray(J – 1))

    lX = CLng(sSplit(0))

    lY = CLng(sSplit(1))

    Sleep hscrlSpeed.Value

    SetCursorPos lX, lY

Next J

End Sub




Figure 2: Mouse Tracer


Initially IPlay contains the total number of elements in sMouseArray. sSplit contains the one group of values of mouse position defined as “X Y”. lX and lY contain X and Y values respectively.  A break or a sleep period is provided as per delay adjusted by the horizontal scrollbar.  The mouse cursor is set to those coordinates by use of SetCursorPos.


The New button acts like a reset button and prepares the system to capture the new movement of the mouse, erasing the previous record. We code it as below:


Private Sub cmdNew_Click()

cmdStop.Enabled = False

tmrMouse.Enabled = False

cmdRecord.Enabled = True

cmdPlay.Enabled = False

I = 0

End Sub


Similarly the Record button indirectly calls the RecordMouse () function by enabling the tmrMouse, which enables us to start the recording procedure.


Private Sub cmdRecord_Click()

cmdStop.Enabled = True

tmrMouse.Enabled = True

cmdRecord.Enabled = False

cmdNew.Enabled = False

End Sub


To stop the recording procedure, we need to click on the Stop button. This enables the play button enabling us to view the movement as many times as we want.


Private Sub cmdStop_Click()

cmdStop.Enabled = False

tmrMouse.Enabled = False

cmdPlay.Enabled = True

cmdNew.Enabled = True

End Sub


Controlling Windows Shutdown through API


Let’s understand one more API function, ExitWindowsEx.  This function helps us to shutdown, log off or restart our computer.

Defining Application Problem


The user selects one of the options from  Shutdown, Restart or Log Off and provides with number of minutes after which the computer should either Shutdown, Restart or Log Off.

Understanding API


Public Declare Function ExitWindowsEx Lib “user32” Alias “ExitWindowsEx” (ByVal uFlags As Long, ByVal dwReserved As Long) As Long


Let’s understand the syntax of this function and then see an application example.


Table 6: Syntax of ExitWindowsEx


Function Name:


Actual Windows Function Name:




Numeric Value



Log Off


Shut down system & Power Off




Shut down system


Reason for initiating the shutdown. This parameter must be one of the system shutdown reason codes.  Since we would like to shutdown for application purpose, we use the code 0x00040000



Table 7: Some of the System Codes for dwReserved





Application issue.


Hardware issue.


The InitiateSystemShutdown function was used instead of InitiateSystemShutdownEx.


Operating system issue.


Other issue.


Power failure.


Software issue.


System failure.


Application Design


Let’s analyze the code.


Global declarations that follow are:


Declare Function ExitWindowsEx Lib “user32” (ByVal uFlags&, ByVal wReserved&)


Const EWX_FORCE = 4

Const EWX_LOGOFF = 0

Const EWX_REBOOT = 2



Public Choice, TimeRequired


The code for starting to Log Off, Shutdown or Restart when user presses Apply Button is as:

Private Sub cmdApply_Click()

   Timer1.Enabled = True

   Timer1.Interval = 1000

   tvalue = Val(Text1.Text) * 60
‘convert minutes to seconds

   TimeRequired = tvalue

   OptLogOff.Enabled = False

   OptShutdown.Enabled = False

   OptRestart.Enabled = False

   CmdApply.Enabled = False

   Text1.Enabled = False

   MsgBox “Timer Starts Now!”

End Sub


Private Sub cmdCancel_Click()

   CmdApply.Enabled = True

   Timer1.Enabled = False


End Sub


To avoid automatic action when the form loads, we provide the following code:


Private Sub Form_Load()

  OptLogOff.Value = False

  OptShutdown.Value = False

  OptRestart.Value = False

End Sub


Private Sub OptLogOff_Click() ‘Log Off

CmdApply.Enabled = True

   If OptLogOff.Value = True Then

      Choice = EWX_LOGOFF ‘user chooses to logoff

   End If

End Sub


Private Sub OptShutdown_Click() ‘Shutdown

CmdApply.Enabled = True

   If OptShutdown.Value = True Then

     Choice = EWX_SHUTDOWN ‘user chooses to shutdown

   End If

End Sub


Private Sub OptRestart_Click() ‘Reboot

   CmdApply.Enabled = True

   If OptRestart.Value = True Then

       Choice = EWX_REBOOT ‘user chooses to restart

  End If

End Sub


The most important part where the API function is called is Timer.


Private Sub Timer1_Timer()

    Static Counter

    If Counter <> TimeRequired Then

       Counter = Counter + 1
            ‘increment our counter if it is not yet time


       vResult = ExitWindowsEx(Choice, 0&)

       Counter = 0


    End If

End Sub




Figure 3: Windows Shutter


The final application after programming appears as shown in Figure 3.  There are various other examples of API such as Graphics Programming, Playing Sounds, Setting up Registry Values, Capturing Screen, Capturing Web cam and many more. 


In our next article in this issue, we focus on Multimedia Programming and consider few applications.

Note: This series was first published in DeveloperIQ and was co-authored by Punit Ganshani with Pranjali Bakeri in 2005-2006.

Visual Basic – Reports and ActiveX Controls

March 15, 2006 Visual Basic, Visual Studio ,

When we store data, we sometimes like to have its report in printed format with the layout as desired by us. This can be achieved by using Data Environment.  And sometimes, some modules made for one applications fit well into other applications.  This task can be done be copying the same piece of code from one application to another or by creating special controls known as ActiveX Controls.

SQL (Structured Query Language)


We have been using SQL since we understood the concepts of database management.  SQL (pronounce as sequel) is the standard language of Relational Database Management Systems (RDBMS) as decided by the American National Standards Institute (ANSI).


Let’s quickly review the different commands of SQL Language.

Type 1: Creating and Deleting Tables







CREATE TABLE tablename

(Field1Name Field1Type, Field2Name Field2Type, etc.);

This command creates a new table with tablename

CREATE TABLE PData (Name TEXT (32), Mobile LONG, Address TEXT(40));

Delete Table

DROP TABLE tablename;”

This command deletes the entire table



These statements can be associated with any database object as:


Data1.Database.Execute “DROP TABLE PData”


Type 2: Selecting Records from Tables







SELECT fields FROM tables WHERE criteria;

Fields is a comma-delimited list of fields to return, tables is list of tables where to find the fields and criteria is an expression that records must satisfy.

Select Name, Mobile from PData where Name = ‘Mr.ABC’;

This selects only those records where the Amount lies between 100 and 200.

Select * from PData where amount between 100 and 200;

This selects only those records in which Code Starts with H, and thereafter arrange the records in ascending order of Name

Select * from PData where code like ‘H*’ order by Name asc;


This command can be linked with database object with either RecordSource Property or ResultSet Property as:


Data1.RecordSource = “SELECT * FROM PData”

Type 3: Executing Commands related to Tables







Update table SET field=newvalue WHERE criteria;

This allows performing update operation on database.

Update PData SET Name = ‘Mr. XYZ’, Mobile=’981112222’ where Name = ‘Mr. Abc’;


DELETE FROM tables WHERE criteria;”

This allows performing delete operation on database.

DELETE from PData where Name = ‘Mr. Abc’;



table (Field1Name, Field2Name, etc)

VALUES (Field1Value, Field2Value, etc);

This allows adding records in database.

Insert INTO PData (Name, Mobile) VALUES (‘Mr. DEF’, ‘9888198822’);


These statements can be associated with any database object as:

Data1.Database.Execute “DELETE FROM PData WHERE Name = ‘” & txtName.text & “’;”

Data Environment & Reports

A Data Environment is a platform on the basis of which the report can be made.  It provides the information to be displayed in the report.  In other words, Data Environment is a back bone to form Data Report.  This, we first need to configure Data Environment as per the information required by us and thereafter work on the Data Report.


Data Environment


We first target at adding a Data Environment and Data Report in our project. To do this, we click the right button in the Project Explorer Window, and add them.


Before creating a report we need to link a Data Environment (that provides a link to the database) with a Data Report. Consider that we are linking a personal database that has Name, Mobile and Address as fields.


In Data Environment, we first add a connection (Right button Click) and then connect a database as we did in ADO.  Thereafter we create a new command in that connection and provide the settings as shown in Figure 1.




Figure 1: Properties of first command (NameDetails)




Figure 2: Setting properties of Parameter.


In Figure 1, we provided with SQL Statement


SELECT * FROM PData WHERE (Name = ?)


Here, PData is the Table Name and Name is one of the fields.  The ? is an external parameter that will be searched for in the Table Records and only those records matching with Name. The properties of the parameters are set from the Parameter Tab as shown in Figure 2.


Data Report and Linking

After this we open the Data Report and link the fields of Database defined in Connection1 as shown in Figure 3. To bring the fields on Data Report, we first cascade the windows and then Drag (From Data Environment) and Drop them on Data Report.


We can add different text labels in the Report Header, Page Header, Page Footer and Report Footer. Resizing these sections as per space desired makes the result compact and appear professional.


When this report is executed, it does not display any records though the database may have it. This is because the value of the parameter defined in NameDetails is undefined.  Let us see how to tackle this situation.


We create a new form that allows the user to enter the name, which is passed as an argument to Data Environment. This argument is accepted as a parameter for NameDetails and accordingly report is generated.


Figure 3: Data Report Format


Private Sub cmdGo_Click()

      Unload DataEnvironment1

      DataEnvironment1.NameDetails (txtSearch.Text)


      Unload Me

End Sub


Here value of txtSearch is the name, whose records we wish to see. In case we wish to see all the records, we either change the SQL statement to


Select * from PData


Or select Table as Database Object and PData as Object Name.




Figure 4: Data Report at the time of Execution


We can provide advanced functions like addition, Average, Multiplication of the fields (Of the Integer or Long type) by using clip_image010 (RptFunction) from the Tool Box.


ActiveX  Controls



ActiveX originated with an aim of designing components for Internet Applications.  These controls, like other Visual Basic controls, can support properties, methods and events.  An ActiveX control can be built as a stand-alone control, or can be built with a dependence on other existing modules (or ActiveX Controls).   The activeX Controls when compiled have the extension (.ocx).


These controls can be re-used in other programs directly by adding these controls through Project Menu > Components.


Programming ActiveX Control


Select File > New Project > ActiveX Control as shown in Figure 5. We change the name of the project to DateControl1. The new form that appears in front of us is actually a control file with .ctl extension.


We place three Text Boxes with their names as txtDD, txtMM, and txtYY as shown in Figure 6.





Figure 5: New Project Dialog Box





Figure 6: DateControl


Let’s code this DateControl1.


Dim mm, dd, yy As Integer

Private Sub txtMM_GotFocus()

If Val(txtDD.Text) > 31 Or Val(txtDD.Text) < 1 Then


End If

End Sub


The above code checks for the validity of date entered by the user in the first TextBox (txtDD), while the code below checks the validity of month entered by the user in the second TextBox (txtMM).



Private Sub txtYY_GotFocus()

If Val(txtDD.Text) > 31 Or Val(txtDD.Text) < 1 Then


End If

If Val(txtMM.Text) > 12 Or Val(txtMM.Text) < 1 Then


End If


mm = Val(txtMM.Text)

dd = Val(txtDD.Text)

If mm = 2 And dd > 29 Then


End If


If mm = 4 Or mm = 6 Or mm = 9 Or mm = 11 Then

    If dd > 30 Then


    End If

End If

End Sub


However, there is one more condition that needs to be checked that is whether the year entered is a leap year and the validity of date entered. The code written below does the same.


Private Sub txtYY_KeyPress(KeyAscii As Integer)

If KeyAscii = 13 Then


End If

End Sub


Private Sub txtYY_LostFocus()

yy = Val(txtYY.Text)

If yy Mod 4 <> 0 Then    ‘not leap year

    If mm = 2 And dd > 28 Then


    End If

End If

End Sub


Just as in forms, Form_Load event executes at the beginning of any form, in this case UserControl_Initialize is executed.


Private Sub UserControl_Initialize()

txtDD.Text = Day(Date$)

txtMM.Text = Month(Date$)

txtYY.Text = Year(Date$)

End Sub

Compiling & Registering the Control


Before compiling, let’s test our control.  To test, we just execute the control as we Run the program.  A Dialog Box asks for the Start Component and as we Click on OK, the control opens in Internet Explorer as shown in Figure 7.




Figure 7: DateControl Testing


Let’s compile it so that we can use this in other projects. 


Select File > Make DateControl1.ocx and save it in C: drive.


To use this ActiveX control in Windows, we need to register it with Windows, which is done by regsvr32.exe utility provided with Microsoft Windows.


C:\>regsvr32 c:\datecontrol1.exe


Since, we have registered this DateControl1, a CLSID is assigned to this control and now this control shall be listed in the Project > Components


Using Control in Other Projects


Let’s remove this project and start a new project afresh.  We include DateControl1 ActiveX Control through Project > Components





Figure 8: Adding DateControl1 ActiveX Control


An icon like clip_image020  appears in the ToolBox. We paste this control on the form the way we used other controls (ADODC and RDO)


Setting Properties


A control is not much useful unless we are able to change its properties and accessing its values.  The values that can be accessed can be defined as Properties. Let’s understand the procedure to do the same.


Select Tools > Add Procedure and do as shown in Figure 9.


Thereafter we provide two different pieces of code as:


Dim minvalue as Integer


Public Property Get MinYearValue() As Variant

MinYearValue = minvalue ‘This retrieves the current value of                                    ‘MinYearValue

End Property

Public Property Let MinYearValue(ByVal vNewValue As Variant)

minvalue = vNewValue    ‘This assign the new value to the property

PropertyChanged “MinYearValue” ‘This makes the property persistent

End Property




Figure 9: Adding Property


The ActiveX stores the properties in PropertyBag Object, so we need to store the values in the PropertyBag.


Private Sub UserControl_ReadProperties(PropBag As PropertyBag)

minvalue = PropBag.ReadProperty(“MinYearValue”)

‘To read store properties.

End Sub


Private Sub UserControl_WriteProperties(PropBag As PropertyBag)

PropBag.WriteProperty “MinYearValue”, minvalue, 1950

‘To write properties.

End Sub


Private Sub txtYY_KeyPress(KeyAscii As Integer)

If KeyAscii = 13 Then


    yy = Val(txtYY.Text)

    If yy < minvalue Then

            ‘Here minvalue is value of MinYearValue

        MsgBox “Year less than that allowed!”

    End If

End If

End Sub


Similarly we visible in Figure 9, we can add Events, Functions and can have their access.


Adding Events


Let’s add an event to check validity of date. We keep event’s name as OnClick. 


There are two concepts to be used in programming of this event.


Suppose we wish to allow the flexibility of calling this Event when the user clicks on the control, then we write the piece of code as


Private Sub UserControl_Click()

RaiseEvent OnClick

End Sub



The code for this event needs to be written in the project in which this ActiveX is used.  As a sample, we code it as


Private Sub DateControl1_OnClick()

    MsgBox “Event has Triggered!”

End Sub


This provides flexibility to the programmer to code the ActiveX Control dynamically through the project in which it is called.


With this we hope that the readers would have received a larger overview of Programming in Visual Basic.  In our next articles, we shall be covering API and Multimedia Programming as well as Application Designing.

Note: This series was first published in DeveloperIQ and was co-authored by Punit Ganshani with Pranjali Bakeri in 2005-2006.

Visual Basic – File & Database Management

February 12, 2006 Visual Basic, Visual Studio ,


File Management


A software must be able to store and retrieve the data that user enters while execution of software.  In this article, we shall understand the different ways to access the file data.


Opening and Reading a File


The syntax for opening the file with Open Command is as,


Open Filename For mode As [#]filenumber [Len=reclength]


Table 1: Arguments of Open Statement



Various modes in which a file can be opened are





The file is opened for reading the data from the file.


The file is opened for writing the data to the file.  This mode creates a new file if the file doesn’t exist.  If it already exists, then the data of the file is overwritten.


The file is opened for editing/adding the data to the previously existing file.  If the file doesn’t exist previously, a new file is created.


The file is opened for random access.


The records are entered in binary format


Each file is referred by a unique filenumber. The range of filenumber is from 1 to 511.  To obtain the next available filenumber, we use FreeFile Function


This defines the maximum length of the file.  It can take values less than or equal to 32,767 bytes.  It is record length for files opened in Random Access mode.


Opening file for Writing /


Consider that we need to store Name and Age of the employees in a file.  This file if opened in Output mode, will store data of one employee rather than keeping the data of all employees.  Hence, it is needed to be opened in Append mode.


The following code will make it clear,


Private Sub cmdReadSimple_Click()

txtRName.Text = “”

txtRAge.Text = “”

Dim s1, s2 As String

Open txtFileName.Text For Input As #2

Do Until EOF(2)                           ‘Search till End-Of-File

    Input #2, s1                          ‘Get data from file

    Input #2, s2

    txtRName.Text = txtRName.Text + s1 + vbNewLine

    txtRAge.Text = txtRAge.Text + s2 + vbNewLine


Close #2

End Sub


Private Sub cmdWriteAppend_Click()

Open txtFileName.Text For Append As #1    ‘Opened in append mode

Print #1, txtWName.Text

Print #1, txtWAge.Text

Close #1

End Sub


Private Sub cmdWriteSimple_Click()

Open txtFileName.Text For Output As #1    ‘Opened in output mode

Print #1, txtWName.Text

Print #1, txtWAge.Text

Close #1

End Sub



The output of the program is shown in Figure 1.  The data entered at the end is xyz and 34.  The other two data’s are added previously in the append mode.



Figure 1: File Opened for writing in Append Mode


When opened in the Output Mode, only last data xyz would remain in the file.


In the function cmdWriteSimple, we open the file mentioned in the text box in Output Mode.  Print statement is used to write text in the file.  The syntax of print statement is as,


Print [#]filenumber, data in text format.


Instead of print statement, Write # Statement can also be used. It assumes the same format as Print statement. 



To Remember:
 The difference between Print and Write statement is that Print statement can only write text on file, while Write statement can write text and other data types also.


The Close statement is used to close the file that was opened by Open Statement.  This close statement inserts End Of File to the file.


In the function cmdWriteAppend, the file is opened in Append Mode.  The rest of the code remains same.


While reading the file, we have used EOF statement in do until loop, which executes the code till End Of File is not detected.


Opening file in Binary Mode / Random Access Mode


The commands for opening the file in Random Access Mode or Binary Mode vary from those mentioned before.


To write data to the file Put statement is used and to retrieve data from the file, Get statement is used.


The syntax of Put and Get statement are:


Put [#]filenumber, [recordnumber], varname

Get [#]filenumber, [recordnumber], varname


This renders us to insert record at a particular record number.


File Related Functions

FileLen and LOF()


Syntax: FileLen(filename)

This function returns the length of the file on disk in bytes


Private Sub cmdLength_Click()

MsgBox FileLen(“c:\data.txt”)

End Sub


A similar function is LOF (abbreviation of Length of File).  The difference in both the functions is that LOF accepts the file number as an argument while FileLen accepts filename as argument.


Syntax: LOF(filenumber)


Private Sub cmdLength_Click()

Open “c:\data.txt” For Input As #1

MsgBox LOF(1)

End Sub

Input$ Statement


Syntax: Input$(characters to be read, filenumber)

It returns the text from the file and stores it in the variable name.


Private Sub cmdRead_Click()

Open “c:\data.txt” For Input As #1

Text1.text = Input$(LOF(1), #1)

End Sub

Seek Statement


Syntax: Seek [#]filenumber, position

Sets the position for the next read/write operation within a file opened using the Open statement.  In Random Access Mode, Seek sets the next record while in all other modes it sets the byte position at which next operation takes place.


Line Input Statement


Syntax: Line Input [#]filenumber, varname

Reads a single line from an open sequential file and assigns it to String Variable


Private Sub cmdRead_Click()

Dim text as String

Open “c:\data.txt” For Input As #1   ‘ Open file.

Do While Not EOF(1)   ‘ Loop until end of file.

   Line Input #1, text   ‘ Read line into variable.

   MsgBox text   ‘ Print to the Immediate window.


Close #1   ‘ Close file.

End Sub


Database Management


Storing data in file can make the file bulky and searching, sort processes can become cumbersome. A better available alternative is use of database.  What makes database different from normal text files is their pre-defined compressed structure.  There are different sets of database objects in Visual Basic. 


Initially, Microsoft introduced Data Access Objects (DAO) to connect Microsoft Jet database engine in Microsoft Access. Later, realizing that there are other datatypes available, they came up with Open Database Connectivity (ODBC) and supported Remote Data Objects (RDO) in Visual Basic.  As internet became more popular and eCommerce concept involved, Microsoft created ActiveX Data Objects (ADO) that can use connections on a single computer over networks.




clip_image005 DAO uses Microsoft Access Database files with extension .mdb. Database can be made either through Microsoft Access or using Visual Data Manager (Add-Ins Menu) of Visual Basic.  We assume that the database has been created and the structure of database is as shown in Table 2 and a part of method of creating database through Visual Data Manager is shown in Figure 2.




Figure 2: Visual Data Manager


There are three fields in the table PData so we need three TextBoxes on the form to bind the data in the database with these TextBoxes.  We then insert the DAO control on the form and the form appears as in Figure 3. 


Table 2: Personal Database


Database Name:



Table Name:


Field Name

Data Type












Thereafter, we set the properties of Data1 and TextBoxes as shown adjacent to Figure 3.



Figure 3: Database Connectivity



RecordSource: PData


DataSource of txtName, txtMobile and txtAddress as Data1



DataField: Name



DataField: Mobile



DataField: Address

If there are any records in the database, we can view them on this form using buttons on the Data1 control.


Let’s now add code to Add New Records in Database, Edit, Delete and Search Records.


Private Sub cmdAdd_Click()


cmdAdd.Enabled = False

cmdEdit.Enabled = False

cmdUpdate.Enabled = True

End Sub


To add a new record, we use AddNew method. 


To edit a record, Edit method is to be called


After the add/edit button is clicked, update button (that updates the record in the database) should be pressed so that the record is entered into the database


Private Sub cmdEdit_Click()


cmdAdd.Enabled = False

cmdEdit.Enabled = False

cmdUpdate.Enabled = True

End Sub


Private Sub Form_Load()

cmdUpdate.Enabled = False

End Sub


Private Sub cmdUpdate_Click()


cmdUpdate.Enabled = False

cmdAdd.Enabled = True

cmdEdit.Enabled = True

End Sub


To update database, we need to use Update Method.

Private Sub cmdDelete_Click()


If Not Data1.Recordset.EOF Then


End If

End Sub


To delete the current record that is visible on the screen, we use the Delete Method. After deleting the record, the record should either move to the next or previous record.


Private Sub cmdSearch_Click()

Dim name As String

Dim isfound As Integer

isfound = 0

name = InputBox(“Enter Name to_
 Search”, “DAO”)


While Not Data1.Recordset.EOF

   If UCase(name) = _

      UCase(txtName.Text) Then

        isfound = isfound + 1

        MsgBox “Press any key to _

    End If



If isfound = 0 Then

    MsgBox “No records found”

End If


End Sub

To search the record, we move to the first record (MoveFirst method) and thereafter check all the records one by one (MoveNext method) till the End Of File (EOF property).


When the record is found, we display the message through the Message Box.




Figure 4: Personal Database Program at Run-time.


The execution of the program is shown in Figure 4.


RDO (Configuring ODBC)


Before using RDO, we need to configure a new connection for ODBC source.  We configure an ODBC connection with 32-bit ODBC item in Control Panel (Control Panel> Administration Tools>Data Sources>System DSN) as shown in Figure 5 and 6.




Figure 5: Creating a new ODBC Data Source




Figure 6: Database db as ODBC database.

clip_image017 To introduce RDO control, select Microsoft Remote Data Control from Components in Project menu.  Thereafter, we connect RDO with the project.


The properties of RDO need to be changed as,


DataSourceName:     db

SQL:                           Select * form UserDB

Figure 7: RDO Connectivity

Here, UserDB has following fields:


Type                Character         1
UserName       Character         30
Password         Character         10





After binding the database UserDB, we do the coding as




For Adding new record


For Updating the record


For Editing the record


For Deleting the record



The code remains the same except that instead of RecordSource, we use ResultSet


Using RDO, we can configure databases remotely and add/modify data in them remotely.  This is an added advantage of RDO over DAO, which is used for local machines.

ADO (ActiveX Data Objects)


clip_image021ADO is a higher version of both DAO and RDO and is generally used for database handling on the Internet. The Adodc objects have an added advantage over the DAO and RDO because not only their properties can be defined through the properties window, but they can be even altered dynamically during execution.


A database can be linked with Adodc in the following manners:

1. Linking through properties of ADODC

2. Linking dynamically using code


Linking through properties of ADODC:

There are various database engines available with us and we need to select one of them.  Let us assume that we are using Microsoft Access Database which uses Jet Engine.  Hence, to link a access file (with extension .mdb) we need to provide a connection string in ConnectionString property of ADODC.


We select Microsoft Jet 4.0 OLE DB as provider, .mdb file as database file. We thereafter, Test Connection to check whether the connection is perfectly established or not. Applying the settings, connection string appears as


Provider=Microsoft.Jet.OLEDB.4.0;DataSource=C:\LMS\MasterDB.mdb;Persist Security Info=False


After defining the connection string, one needs to define the RecordSource, i.e. the table in the database which we wish to refer to.


select * from bookTable


Above is a SQL Statement that enables us to retrieve data of all the fields of the table (here bookTable).  With the knowledge of SQL, we can have selected records to be displayed and can omit the ones not required.  Sorting of records can also be done.


Thereafter, we link the data fields’ to textboxes and labels as desired and program the same way as we did in DAO.  However, there’s one exception of ADO from DAO that we don’t need to write the code for editing.  It prefers to edit automatically once the key is pressed on any of the fields.  We just need to update the database so that the changes made are reflected the next time.


Visual Basic provides an easier method to do the same by the concept of VB Data Form Wizard. This wizard creates a raw form for accessing the database with the help of ADO or RDO.


Let’s create a new form of type VB Data Form Wizard.   A window appears that asks for the profile.  We select the default value (None) and proceed ahead.





Figure 8: Data Form Wizard – Profile


Thereafter, we select the type of connection: Access (ADO) or the ODBC(RDO) Interface.  The database link is to be provided in the next page after you select Access Interface, which we provide as C:\LMS\MasterDB.mdb.


We then need to decide the name of the form in the next screen that appears.



Figure 9: Data Form Wizard – Form Layout


We proceed ahead keeping the form layout as Single Record. We will have direct data access with the help of adodc object named datPrimaryRs, which is automatically kept by wizard.  Here, the Binding type is ADO Data Control.  We shall consider ADO Code in the second style of ADO Connection.


We can also use other layouts as per requirements.




Figure 10: Data Form Wizard – Record Source


The Record Source is the table of the database which we need to access. The selection of available fields (in the table defined in Record Source) determines the way(order) in which we want the form components to be placed.


Column to Sort By defines by which field one wants to sort the entry into the database.  Thereafter, we finish this procedure and a form as shown below is created by the wizard.




Figure 11: Data Form Wizard Output – ADO Binding


In cases, where we need to link data of two tables, we use an alternative layout called Master/ Detail. We can link them by a common data field.  Here, we have used Student ID as linking data field between StudentRecords table and IssueRecords table and the result is



Figure 12: Data Form Wizard Output – Linking of two databases


Let’s now understand the second method i.e. ADO Code.  We repeat the same process without setting the properties of ADODC and rather by code.


Let’s understand the code written below:


Global Definition:

  Dim WithEvents adoPrimaryRS As Recordset

  Dim db As New ADODB.Connection


On Form Load:

  db.Open “PROVIDER=Microsoft.Jet.OLEDB.3.51;Data _  Source=C:\LMS\masterdb.mdb;”  ‘Which database to use


  Set adoPrimaryRS = New Recordset

  adoPrimaryRS.Open “select Type,UserName,Password from UserDB“, db,_
      adOpenStatic, adLockOptimistic

      ‘Type,UserName and Password are fields in table UserDB

  Dim oText As TextBox  ‘oText is a general TextBox

      ‘Bind the text boxes to the data provider

  For Each oText In Me.txtFields

    Set oText.DataSource = adoPrimaryRS   ‘Bind textbox to adoPrimaryRS



In the above code, there’s an array of textboxes called txtFields to which the data is binded.  The rest code of Add, Update, Refresh buttons remains same as DAO.  However, the other way of coding for Add Button can be as:


db.Execute “insert into UserDB values(”

      & txtFields(0).Text & ” , ‘”

      & txtFields(1).Text & “‘,'”

      & txtFields(2).Text & “)”


Similarly, using SQL Queries Update and Delete, we can write code for Update and Delete button.


Note: This series was first published in DeveloperIQ and was co-authored by Punit Ganshani with Pranjali Bakeri in 2005-2006.

Visual Basic – Menus and Advanced Controls

February 10, 2006 Visual Basic, Visual Studio ,

With this article, we tend to look higher with/in Visual Basic.  This article introduces to the reader, the method to introduce menu system, and some advanced controls like Rich TextBox, Toolbar, Status Bar and Progress Bar.

Menu System


In almost all the applications the menu system is used to navigate through the software and to access the features in the software.  The menu system is not visible in the ToolBox and is rather available in Tools Menu or can be directly called by CTRL E.  The menu editor appears as shown in Figure 1.



Figure 1: Microsoft Visual Basic Menu Editor


As shown above the Caption (one which will be visible on the screen) in &Bold and the Name is mnuBold.  The shortcut to access the menu is CTRL B.

Private Sub mnuBold_Click()

text1.FontBold = True ‘ code for making the text bold

End Sub


This menu appears as shown in Figure 2.



Figure 2: Menu Created through Visual Basic.


The options Bold, Italics and Underline are indented and are accessible under the top level menu Font.  The shortcuts of the entire menu are displayed on the right.  These shortcuts can not be assigned to top level menu (here Format or Font, as they have child menu under them.)


The Next Button is used to add a new menu item.  Insert Button is used to add a menu item between two existing menus.  The left arrow indents a menu item, while the right arrow does the reverse.  The Up and Down arrows are used to move the currently selected item.


Some menu items can be disabled by removing the Tick from the Enabled CheckBox. Similarly they can be made visible or can be provided by the tick by the option sown in Figure 1.

To add separator


As visible in Figure 2, there’s a separator between Font and Bullets.  To include the separator, we set the caption to “-“, as shown in figure 1.  We can create an array of separators by keeping the name as mnuLine and setting different values of Index.

Adding a Pre-defined Menu


Visual Basic provides us inbuilt facility of pre-defined menus.  This makes our programming easier and faster.  To view the ready-to-do menus, we open Visual Component Manager from View Menu.  We select the Menus from the different Templates available to us.  Let’s try selecting File Menu and see what happens.  On double clicking on File Menu, a new menu is added to our project. However the code for this menu needs to be written by us.



Figure 3: Visual Component Manager


Adding a Pop-Up Menu


Pop-Up menus are those menu’s that appear when we right click on the Visual Basic form.  To create such a menu, we first create a menu through Menu Editor and then keep its visibility OFF. Thereafter, we write a code in the object code window as shown below.


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

If Button = vbRightButton Then      ‘For Right Button

    PopupMenu mnuEdit

End If

End Sub




Figure 4: Pop-Up Menu


Similarly we can add menu’s for left button and middle button by using constants; vbLeftButton or vbMiddleButton instead of vbRightButton.


Adding or Removing Menu Items while Runtime.


We can add or delete menu items dynamically by using Load and Unload functions. Before this, we need to make a controlled array of the item to which we need to add/remove the menu.  We initially assign the Index as 0 and visible as False as shown in Figure 5.





Figure 5: Designing Extendable Menu’s


The code is written as below:


Dim i As Integer

Private Sub cmdAdd_Click()

Load mnuFileItem(i)

mnuFileItem(i).Caption = "New Item" & Str(i)

mnuFileItem(i).Visible = True

i = i + 1

End Sub


Private Sub cmdRemove_Click()

Load mnuFileItem(i)

mnuFileItem(i).Caption = "New Item" & Str(i)

mnuFileItem(i).Visible = True

i = i + 1

End Sub


Private Sub Form_Load()

i = 1

End Sub

Advanced Controls

Rich TextBox


clip_image012 The TextBox doesn’t provide us with facilities of formatting the selected text.  The whole of the text gets formatted which is not intended.  The Rich TextBox can be added through Components option in Project Menu and selecting Microsoft Rich TextBox Control.  This TextBox appears similar to a normal TextBox but has some additional properties, which renders us various other formatting facilities which will be dealt in later sections.





Figure 6: RTB Demonstration


Table 1: RTB Features


Property/ Code


SelAlignment Property assumes three values: rtfLeft for Left Alignment (default), rtfCenter and rtfRight for Center and Right Alignment.


SelBullet Property when set to true inserts bullet to the selected text. The indent to be provided is set by BulletIndent property.

Superscript and Subscript

SelCharOffset Property accepts a positive integer value to Superscript a text and a negative integer to Subscript the selected text.

Bold, Italics, Underline, StrikeThru

The properties SelBold, SelItalic, SelUnderline, SelStrikeThru when set to True do the formatting of the selected text accordingly.

Searching and Replacing

The Find Method accepts the text to be searched as an argument and finds out the text in the Rich TextBox.  To replace the text searched, we set SelRTF property as the new text.

Open A File

FileName property is used to the file whose contents are to be displayed in the RTB.

Save File

SaveFile Method has filename as first argument and type of file as the second argument.  There are two types of file:

Second Argument

Type of File


This file saves the formatting done and this file can be opened in Microsoft Word


This file is saved in Notepad format without saving the formatting.

The above commands are illustrated in the program code written below,


‘Code for Alignment


Private Sub cmdLeft_Click()

rtxtText.SelAlignment = rtfLeft     ‘Align to Left

End Sub


Private Sub cmdCenter_Click()

rtxtText.SelAlignment = rtfCenter   ‘Align to Center

End Sub


Private Sub cmdRight_Click()

rtxtText.SelAlignment = rtfRight    ‘Align to Right

End Sub


‘Adding Bullets


Private Sub cmdBullets_Click()

rtxtText.BulletIndent = 50          ‘Bullet Indent set to 50

rtxtText.SelBullet = True           ‘Give a bullet.

End Sub


‘Subscript and Superscript


Private Sub cmdSubScript_Click()

rtxtText.SelCharOffset = -60                    ‘Lower the letter

rtxtText.SelFontSize = rtxtText.SelFontSize – 1 ‘Decrease the font size

End Sub


Private Sub cmdSuperScript_Click()

rtxtText.SelCharOffset = 40                     ‘Raise the letter

rtxtText.SelFontSize = rtxtText.SelFontSize – 1 ‘Decrease the font size

End Sub




Private Sub cmdBold_Click()

If rtxtText.SelBold = False Then

    rtxtText.SelBold = True


    rtxtText.SelBold = False

End If

End Sub


Private Sub cmdItalics_Click()

If rtxtText.SelItalic = False Then

    rtxtText.SelItalic = True


    rtxtText.SelItalic = False

End If

End Sub


Private Sub cmdStrikethrough_Click()

If rtxtText.SelStrikeThru = False Then

    rtxtText.SelStrikeThru = True


    rtxtText.SelStrikeThru = False

End If

End Sub


Private Sub cmdUnderline_Click()

If rtxtText.SelUnderlined = False Then

    rtxtText.SelUnderlined = True


    rtxtText.SelUnderlined = False

End If

End Sub


‘Search and Replace


Private Sub cmdSearch_Click()

rtxtText.SelStart = rtxtText.Find(txtSearch.Text)‘Find the text

rtxtText.SelUnderline = True                    ‘Underline the text

End Sub


Private Sub cmdReplace_Click()

rtxtText.Find (txtSearch.Text)      ‘Search the text

rtxtText.SelRTF = txtReplace.Text   ‘Replace the searched text

End Sub


‘Open, Save and Print


Private Sub cmdOpen_Click()

rtxtText.FileName = "c:\data.txt"   ‘Opens the file data.txt

End Sub

Private Sub cmdSave_Click()

Dim file as String

file = InputBox("Enter FileName")   ‘Input filename from user

If MsgBox("Do you want to save in RTF format", _

vbYesNo) = vbYes Then

    rtxtText.SaveFile (file),rtfRTF  ‘Save in RTF format


    rtxtText.SaveFile (file),rtfText ‘Save in Notepad format

End If

End Sub

Private Sub cmdPrint_Click()

Printer.NewPage                     ‘Create a new page on printer.

rtxtText.SelText = rtxtText.Text    ‘Select entire text of the TextBox

rtxtText.SelPrint (Printer.hDC)     ‘Print it on the printer
End Sub



clip_image016 There are some commonly used controls in Windows like Toolbars, Status Bar, Progress  Bar.  These controls are available in Microsoft Windows Common Controls, which can be accessed through Components in Project Menu.



Figure 7: Common Controls

We can add different toolbars to the form.  After pasting the toolbar on the form, we need to right click on it to access the properties.


On the Button Tab in the properties, we can insert the Buttons as shown in Figure 8.




Figure 8: Addition of Buttons


The code when the button is clicked is to be written in,


Private Sub Toolbar1_ButtonClick(ByVal Button_
      As ComctlLib.Button)

End Sub


Pictures can also be added using Image Property mentioned under General Tab




Figure 9: Rich TextBox with toolbars

Private Sub_

Toolbar1_ButtonClick(ByVal_ Button As ComctlLib.Button)

If Button = "Bold" Then


ElseIf Button = “Italics” then

ElseIf Button = “Underline” then
ElseIf Button = “Bullets” then

End If

End Sub


There can be different types of buttons in a tool bar, which can be accessed by the Style Property under the Buttons Tab.


Table 2: Styles of toolbars




The ToolBar Button acts as a PushButton and remains pressed until re-pressed


Only one butoon of the entire group can be accessed. It acts as an Option Button


It provides an aesthetic appearance by providing a separator in between the two Buttons


Provides a ComboBox in the Tool Bar.  The width should be mentioned in the Button Tab so that a proper space is left between the two buttons.  Thereafter, a combo box should be placed externally.


A toolbar can be added dynamically while run-time by the following method.



Figure 10: Toolbars added at runtime

Dim i As Integer


Private Sub cmdAdd_Click()

Dim button1 As Button

Set button1= _ Toolbar1.Buttons.Add()

button1.Style = tbrDefault

button1.Caption = txtText.Text

End Sub



Status Bar


clip_image026 The status bar is sometimes used as mini-help for application.  This bar is used to show the status of an operation and hence it is named as Status Bar.  We can add Panels to the collection by right clicking on the status bar and accessing the properties.  The text to be displayed in Panels can be coded as,


Private Sub Form_Load()

StatusBar1.Panels(1).Text = "Form Loaded"

End Sub


The status bar can display various pre-defined texts such as date, time and key status as per the Style defined:


Table 3: Styles of Status Bars


Text displayed


For normal text or picture


Caps Lock Status


Num Lock Status


Insert Status


Scroll Lock Status


Current Time




Similarly, we can have Raised, Bevel or Inset appearances of the status bar which can be set through the Appearance property.




Figure 11: Property of StatusBar


The events can be called when the user clicks on any panel of the status bar.  Each Panel has a unique key and with this key, one can code as shown below:

Private Sub StatusBar1_PanelClick(ByVal Panel As ComctlLib.Panel)

Select Case Panel.Key

    Case "status"       ‘first Panel with Key status

        Panel.Text = "hi"

End Select

End Sub


A sample code is shown below to display picture in the status bar.


Private Sub cmdPicture_Click()

      StatusBar1.Panels(2).Picture = “c:\back.jpg”

End Sub


Progress Bar


clip_image030 A progress bar is used to show the progress of the process.  We often see this type of progress bar in the applications such as Adobe Photoshop. The coding of the Progress Bar is similar to that of a slider. We decide the range of the Progress Bar by Min and Max Properties. The value of the Progress Bar is indicated by the Value Property. We normally associate the value of the Progress Bar with that of a Timer.


A sample code is shown below


Private Sub Timer1_Timer()

If ProgressBar1.Value < 100 Then

ProgressBar1.Value = ProgressBar1.Value + 10

                        ‘ increase value of progress bar


    Timer1.Enabled = False    ‘stop timer

    MsgBox "Processing Done"  ‘display that 100 % is done.

End If

End Sub



Figure 12: Progress Bar

The code can assume complicacies as per the process.  We have shown one example of opening a file which has a progress bar which appears embedded inside a status bar. 


Dim file As String


Private Sub cmdOpen_Click()

file = "c:\data"

rTemp.FileName = file

Timer1.Interval = Len(rTemp.Text)

Timer1.Enabled = True

End Sub


Private Sub Timer1_Timer()

If ProgressBar1.Value < 100 Then

ProgressBar1.Value= ProgressBar1.Value_
      + 10

= Str(ProgressBar1.Value) + " %"


    rtxtFile.Enabled = True

    rtxtFile.FileName = file

    Timer1.Enabled = False

    StatusBar1.Panels(1).Text = "Done"

    ProgressBar1.Visible = False

End If

End Sub



Figure 13 (a): While processing




Figure 13(b): After processing.



The other controls highlighted in the Figure 7 can be programmed easily with the knowledge of controls covered in this article. In our next articles, we shall cover the File Management and Database Management.

Note: This series was first published in DeveloperIQ and was co-authored by Punit Ganshani with Pranjali Bakeri in 2005-2006.

Visual Basic – Understanding Controls – Part II

February 10, 2006 Visual Basic, Visual Studio ,

In our previous article, we considered few of the many controls in Visual Basic.  In this article, we aim at understanding other standard controls and basic programming techniques and standard statements.

Controls Continued



We have seen two methods to provide choices to user i.e. by using Option Buttons and CheckBoxes.  But both Option buttons as well as Check boxes fail when the number of options exceeds a certain limit as they are bound to go out of the screen.  List boxes can be an alibi for the same.


There are two ways to set the items / choices of the ListBox.  Once the number of items is fixed, we can add them in the List property and hence can populate the list. The other method to add items in the list is to add dynamically through our code.  Both methods are illustrated in Figure 1.




Figure 1: Two Methods of Setting List


After having the items in the list, the focus is to find out which option has been selected by the user.  There are again two methods to do the same (Table 1).


Table 1:  List Box Access Methods


Method One: Referring the items by ListIndex property

Method Two: Referring the items by Text property

Private Sub lstOptions_Click()

If lstOptions.ListIndex = 0 Then

      MsgBox lstOptions.Text

End If

End Sub

Private Sub lstOptions_Click()

If lstOptions.Text = “Item1” Then

      MsgBox lstOptions.Text

End If

End Sub



In the first method, the list items are referred by the index number which starts from 0 to n-1, where n = total number of items, given by the ListCount property. While in the second method, we refer the items by the Text property. 




Figure 2: Scrollbar in ListBox

The scrollbars are automatically added once the number of item exceed the number that can fit in the area of the ListBox, which is shown in
Figure 2.



We can remove the items dynamically by using RemoveItem(integer) as shown below. To remove all the items, we can use the function Clear()




Figure 3: Remove & Clear


‘Clears complete list

Private Sub cmdClear_Click()


End Sub


‘Removes Specific Item from List

Private Sub cmdRemove_Click()

lstOptions.RemoveItem (lstOptions.ListIndex)

End Sub




There are some other baby versions of ListBox.  One of the modifications allows us to have list of check boxes in list.  This can be done by setting the value of Style property as 1-Checkbox.  The other version allows us to have multiple selections in a list.  This is done by setting MultiSelect property to 1-Simple.  The user can hence select or deselect any item in the list. By setting its value to 2-Extended, the user can use shift key to select multiple items at a stroke.  Both the versions are illustrated in Figure 4.





Figure 4: Different Versions of ListBox



The number of selected items can be known through the SelCount property of the ListBox. We can also have one more version having more than one columns, which can be set by Columns property to a numeric value greater than 0. This adds a horizontal scrollbar if the list does not entirely fit.  By using the Sorted property to True, we can alphabetically sort the list.




ComboBoxes are similar to ListBoxes with few limitations like we can not have multiple columns in ComboBoxes.  The procedure to add/remove/clear the items in the ComboBoxes is similar to that of ListBox.  The benefit of using ComboBox is that it occupies lesser space than ListBox with same number of items. 



Figure 5: ComboBox Example

Secondly, ComboBox displays just one item and on clicking the drop box, the other items are visible.  The same example of ListBox is implemented using ComboBox, which is shown in Figure 5.



When the Locked property is set to True, the user can see the drop down list but can not select any item from the ComboBox.




There are two types of ScrollBars i.e. Horizontal and Vertical Scrollbars. The range of the ScrollBar can be set to the Min and Max properties of the Scrollbar. The current position of the slider in the scrollbar is indicated by Value property.


When the arrows of the scrollbars are clicked, the value of the scrollbar changes by an amount as defined in the SmallChange property.  When the user clicks on the area between the slider and the arrow, the value changes by an amount as defined in the LargeChange property.



Figure 6: Illustration of Scrollbar

Private Sub HScroll1_Change()

      txtValue.Text = HScroll1.Value

End Sub


Here, the range is 0 – 100.
The SmallChange is set to 1,
while LargeChange is set to 10.

Depending upon the value of scrollbar, either a text or picture can be rotated.  One such application is file explorer (like Windows Explorer).

Picture Box & Image Box


A picture box is used to display picture that is mentioned in Picture property.  If the size of the picture is bigger than the Picture Box, then the picture is not compressed and we can see only a small part of the picture.  Setting the AutoSize property to True re-sizes the picture box to adjust to the picture size.




Figure 7: PictureBox and ImageBox Illustration


The acceptable forms of pictures in picture box are .BMP, .GIF, .JPG, .WMF and .ICO.  Animated picture file(s) will not animate on the form.  The similar function is done by ImageBox with few exceptions.  The ImageBox has Stretch property.  When Stretch property is False, ImageBox acts like PictureBox and when Stretch property is True, the picture gets compressed into pre-decided area of ImageBox. 



To Remember:

The difference can be seen in the Figure 7. The original image is 800×600 pixel image.  In the picture box, part of the picture that can fit into the box, while in the second case, the complete image is compressed to fit into the same space.  However, this might result into distortion of the Image.


We can assign the picture in the ImageBox and the PictureBox dynamically by LoadPicture() function as shown below


Private Sub Form_Load()

Picture1.Picture = LoadPicture(“C:\Pictures\17.jpg”)

End Sub


Private Sub cmdReset_Click()

Picture1.Picture = LoadPicture(“”)

‘this removes the picture fromPictureBox

End Sub


Another method is to use Cls Property as Picture1.Cls instead of
Picture1.Picture = LoadPicture(“”)


One of the most important applications in Image Processing is accessing the pixels of picture box.   The color of the pixel can be obtained by Point function.


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

Form1.BackColor = Picture1.Point(X, Y)

End Sub

In the above code, the color of the form changes to the color of the pixel where the mouse is clicked.  


Various commands associated with picture are listed below:


Table 2:  Different Commands associated with PictureBox



Command / Property


Printer.PaintPicture picture x1, y1




SavePicture picture, filename

Clipboard Related Functions



Copy to Clipboard

Clipboard.SetData picture

Retrieve from Clipboard

picture =Clipboard.GetData()

Printing Text in PictureBox

Picture.Print(“text here”)

The position of the text is defined by Picture.CurrentX and Picture.CurrentY

Graphic Functions

Pset for setting point

Circle for drawing circle

Line for drawing line


Coding Fundamentals


Let’s understand the fundamentals of coding.  In the first article, the declaration of variables was considered.  While declaration, we were defining the type of variable.  In case we forget to define the variable, still the program would execute but may result into erroneous or unexpected results. To avoid such complicacies, we place Option Explicit in the General Declaration Section of the form code.


While declarations of variables or constants, we sometimes need to assign the values to them, which can be done by two methods,


Table 3:  Initialization of Variables


Method 1

Method 2 (Has become obsolete)

Dim name as String

name = “Visual Basic”

Dim name as String

Let name = “Visual Basic”


Setting properties of controls


Setting properties of a specific control can be done by two methods. Both are illustrated below:


Table 4:  With … End With Block


Method 1 (Has become obsolete)

Method 2

Text1.Text = “VB”

Text1.BackColor = vbBlue

Text1.ForeColor = vbWhite

Text1.MaxLength = 20

With Text1

    .Text = “VB”

    .BackColor = vbBlue

    .ForeColor = vbWhite

    .MaxLength = 20

End With


As shown above, the first method uses repetition of the control name, while the second method uses  With…End With block


Suppose we need to set the properties of a control in some other form (with name FormName) apart from the form in which we are working, we use exclamation ‘!’ operator as,


With FormName!ControlName




End With


This can be used to change the properties of a control on the based of conditions in form calling the called form.




To comment means to describe the purpose of the statement or function used in our code.  The comments are not visible to the user of the program but they increase the readability of the program.  These lines are not compiled by our compiler and hence commenting doesn’t increase the size of our executable file.


There are two methods to comment in Visual Basic,


Method 1: Use of apostrophe

Use of apostrophe () before the comment statement


lblDate.Caption = “Date: ” + Date$   

‘This displays today’s date as in System


Method 2: Use of Rem Statement.


lblDate.Caption = “Date: ” + Date$

Rem This displays today’s date as in System


This method was been used in earlier times of BASIC Programming and was later adopted in Visual Basic Programming.  But this method has now become obsolete.


Breaking Lengthy Statements


When the statement (a piece of code) is too long, it can be broken into two or more parts using underscore (_) operator.  The underscore operator can be placed in between the statement and the next statement can be broken down on the next line.  Note the indentation done, which improves readability of the code.  This can be illustrated as,


If (txtA = “a” And txtB = “b” And txtC = “c”) Or _

    (txtA = “b” And txtB = “c” And txtC = “a”) Then

      ‘See the use of underscore operator

    MsgBox “work done”

End If



The maximum number of such continuations that we can have is 24.


Multiple Statements on a Line


It is possible to have more than one statement on a single line.  The compiler differentiates the two statements by a colon (:).


Table 5:  Multiple Statements on Line


Normal Method

Multiple Statements on a line

For i=1 to 10

 x(i) = 7*i


For i=1 to 10: x(i) = 7*i: Next



Considering Error Conditions


While runtime, there are some unpredictable errors that can occur.  These errors hinder the successful execution of our program.  To avoid this, we include a statement On Error in the function through which there are possibilities of generation of error. 


The syntax of this statement is


On Error Goto label

On Error Resume Next

On Error Goto 0


On occurrence of error the first statement causes a jump in flow of execution to an existing label in the same function. The second statement causes the next statement to be executed, hence ignoring the error.  The third statement discards any error occurring at the time of execution of program.


One such example is shown below,


Private Sub Command1_Click()

On Error Goto to ErrorHandler



‘code follows here




      Msgbox err.description

End Sub


This type of coding has a flaw.  Even if there are no errors while execution, the statements of ErrorHandler label are executed.  To avoid this, we include another statement Exit Sub before ErrorHandler. 


Private Sub Command1_Click()

On Error Goto to ErrorHandler



‘code follows here

Exit Sub ‘breaks the flow of execution



      Msgbox err.description

End Sub

Multiple Forms


In a project having multiple forms, we can define the startup form, which should be displayed the first.   This is done by Project Properties in the Project Menu.




Figure 8: Project Properties


Along with the startup form, we can set project description and Project Name (here, ESystems) that should be displayed as the Title of the Message Box.


In our next article, we aim to cover few advanced controls in Visual Basic and their coding.

Note: This series was first published in DeveloperIQ and was co-authored by Punit Ganshani with Pranjali Bakeri in 2005-2006.


Visual Basic – Understanding Controls – Part I

January 10, 2006 Visual Basic, Visual Studio

Visual Basic programming can be said as programming the controls that are used in the form.  But behind the curtains, there are some fundamental programming concepts on the basis of which our project is built.  We shall cover if-elsestatement as this shall be used in this article.


If-else statement

If expression Then
    ‘Do this
ElseIf expression2 Then
    ‘Do this

    ‘Default if none of the above conditions is true.

End If


The if-else block starts with If statement and ends with an End If statement.  When the expression in the statement proves to be true, the statements written just next to Then are executed.


Two or more conditions can also form an expression using And, Or, Xor, Not operators.


Table 1: Expressions in If-Else Statement.




a=2 And b=3

a=2 and b=3 then only statements are executed

a=2 Or b=3

a=2 or b=3 or both are true, then only statements are executed

a=2 Xor b=3

Either a=2 or b=3 then only statements are executed.

Not a

When a assumes a non-zero value, then statements are executed




Just as in other languages like C, there is scanf() and in BASIC its input command; there’s a text box through which one can input values to the program.  Using Visual Basic, gives us an added advantage of displaying text entered as Bold, Italics or Underlined.


The text entered in the TextBox is stored in its Text property.  To access a TextBox with Name txtName, we need to code as


MsgBox txtName.text


Here, the command MsgBox prompts the value of text (String) entered by user. The dot “.” operator is used to access the properties of the control desired.




Figure 1: Accessing Properties of a control


To convert String data into Integer data, we use val() function as shown below.  Thereafter, we can perform any mathematical operations on the converted data.


Dim age as Integer

age = val(txtAge.text)


The text entered by the user can be aligned to Left, Right or Center.  This is done by using Alignment property.  The maximum number of characters a text box can accept can be defined in MaxLength property of the same.  By default, its value is 0, which states that the max length is not defined. We can select the text in the TextBox and this text is stored in SelText Property, while SelLength indicates the length of the number of characters in the selected text.


The PasswordChar Property is set to a symbol (normally *) to enter password(hidden text).  To have Multiple Line text boxes, in order to have data such as address, we can set MultiLine property as true. We can also add scrollbars by using the ScrollBars Property.


There are various events that are generated when a user types anything/clicks on the text box. They are as,


Table 2: Commonly Used Events (*also used in other controls)



Activated When


User clicks on an object (here TextBox)


User double clicks on an object (here TextBox)


As soon as a key is pressed or on every stroke of keyboard

KeyPress(KeyAscii As Integer)*

As soon as a key is pressed or on every stroke of keyboard.  The ASCII value of the keypressed is stored in KeyAscii



When the TextBox gains/loses focus from/to another object, this event is activated.



Limitation of TextBox:

We cannot change the font of a selected text. The font of the entire text box changes. This can be removed by using RTF TextBox.



To Remember:

It is not preferable to use a TextBox to display text; rather a Label should be used.  In case, one uses text box for same, TextBox property of Enable should be kept False.




A label is use to display some information on the screen (here the form).  It has same properties as of TextBox but its functionality is different.  To avoid confusions between the form color and the label color (which is normally preferred to be same), the BackStyle property is set to Transparent, which renders the backcolor of label as that of form. We can make the label appear just like a TextBox by changing its display properties by setting the BorderStyle property as Fixed Single and BackColor property as White.




Figure 2: Different forms of Label


Though they both appear the same, we can’t input text from user in lblOne.  The other forms of label are lblTwo and lblThree (available by altering the above mentioned properties.)


The text visible as label is set in the Caption property of label.

Wordwrap property expands vertically or horizontally to fit the text specified in its Caption property provided Autosize property is set True. (See lblThree)




The button’s such as Ok, Yes and No that we often see in windows, are command buttons. These buttons normally have a shortcut key to access them such as ALT + O for Ok. To create such shortcut keys for command buttons, we need to place ‘&’ (Ampersand) symbol before a specific character in the Caption Property.  Few such examples are illustrated in Table 3.  The (object) name should have a prefix cmd as a standard.


Table 3: Setting Caption of CommandButton


Caption Property

Shortcut Key