Home > Articles > Programming > Visual Basic

  • Print
  • + Share This

Caller ID with Visual Basic

Caller ID is a service provided by the telephone company that lets you know the caller's name and/or number on a display screen, much like an office phone system. The information is transmitted between rings so that you can see the information before picking up the phone.

In this age of unsolicited telemarketing calls, Caller ID is a great invention, but of course there's a catch: To screen calls, you have to be near the display unit when the phone rings—that is, unless you write the Visual Basic program described in this section (see Figure 23.1). This program simulates the standard Caller ID display box with one addition—sound. When the phone rings, this program plays a sound file that you assign to a specific caller. For example, you can have the computer sound card scream "Don't answer it!" when the telemarketers make their rounds.

Figure 23.1

The Caller ID program alerts you by playing a sound file.

Although this application is fairly specific, in building it you learn a way to communicate with a modem from Visual Basic, a technique that can be applied to other areas.

Requirements for Using the Sample Program

Because this program interacts with the "real world" to some degree, you must follow some basic requirements to use it:

  • You have to subscribe to a Caller ID service.

  • You must have a modem that supports Caller ID data attached to the phone line.

  • You have to know the commands to get your modem to display the data and the exact format in which it will be displayed.

Before you even get into Visual Basic, you should determine the commands necessary to use Caller ID with your modem and test it in a terminal program such as HyperTerminal. For example, issuing the command AT#CID=1 to my modem causes it to activate Caller ID display. Then, whenever the phone rings, the information is presented in the terminal session as follows:

RING

DATE = 0417
TIME = 2005
NMBR = 9015551212
NAME = SILER BRIAN
RING

NOTE

The format and Caller ID implementation vary from modem to modem. For example, my ISDN modem returns the information in an entirely different manner. Although you can easily modify this program to suit your modem, being familiar with your modem's Caller ID format is imperative.

After you have determined how to get the Caller ID information from your modem using a terminal session, the next step is to write a Visual Basic application that talks to the modem, receives this information, and takes action based on it. The sample application described in this section issues the command to turn on Caller ID display; it then repeatedly polls the modem to check for Caller ID data. If any data appears, the program plays the appropriate WAV file. The heart of this program is the Microsoft Communications (MS Comm) Control, which is the component that allows you to talk to the modem from VB.

VB Techniques You'll Be Using

In addition to the newly covered MS Comm Control, this program brings together some material covered in other chapters of the book: INI files, the Timer control, and API calls. In order to successfully complete this example, you should have a good understanding of each of these concepts.

Playing Sounds

An API call is used to play sounds on the computer's sound card. This specific example is covered in Chapter 20, "Accessing the Windows API." Refer to that chapter if you need help using the sndPlaySound API call.

      See "Useful API Calls," p. 457.

Using Intervals

The Timer control, covered in Chapter 4, "Using Visual Basic's Default Controls," is used to initiate the process of checking for Caller ID data. In the sample program, the Timer event is coded with only a single line as follows:

Private Sub tmrMain_Timer()

    CheckForCall

End Sub

CheckForCall is a custom function you will write that checks the modem for new information.

      See "Special-Purpose Controls," p. 78

The INI Configuration File

An INI file stores the information about each call as well as the path to the WAV file you want to play for each caller. You could, of course, store this information in a database or other file, but I picked an INI file because it has low overhead and is easy to edit. A sample INI file is shown here:

[General]
ComPort=3
InitString="AT#CID=1"
CallCount=3

[XREF]
VANDELAY INDUST=Dad at Work
PIERCE JAMES J=Nelda and Jerry Pierce
TAYLOR TECHNOLOG=This is a sales call, don't answer!
MEMPHIS, TN=Cellular phone in Memphis

[Sounds]
PAY PHONE=D:\wav\Dad.wav
VANDELAY INDUST=D:\wav\Hello.Wav

[Call1]
Time=05/25 03:05 p
Number=901-362-6030
Name=LAZENBY N D

[Call2]
Time=05/25 09:31 p
Number=901-555-1212
Name=PRENTICE BRUCE

[Call3]
Time=05/26 12:43 p
Number=901-754-7222
Name=FRIDAY JOE

The INI file is divided into a few basic sections:

  • [SOUNDS]. This section contains the path to the WAV file for each caller name.

  • [XREF]. This section contains a "friendly name" to display for the caller instead of the phone company name.

  • [CALL##]. The program creates a new section as each call is received.

  • [GENERAL]. This section contains the current number of [CALL] sections, as well as some initialization information.

The program uses the INI wrapper functions sGetINIString and writeINIString described in Chapter 21, "Working with Files," to manipulate the INI file.

      See "Understanding INI Files," p. 484.

Starting Out with the Program

The next section will focus on the new material related to the communications control. However, if you are following along, complete the following steps to get started:

  1. Start a new Standard EXE project.

  2. Add a module to the project.

  3. Add the code from Chapter 21 necessary to access INI files.

  4. Add the code for the sndPlaySound API call from Chapter 20.

  5. Draw a Timer control on the form, tmrMain, and set the Interval property to 900.

  6. Make Sub Main the Startup object for the project.

  7. You can also begin creating your INI file, using the sample in the preceding section as a model.

Setting Up the Communications Control

The Microsoft Communications (MS Comm) Control allows your Visual Basic programs to transmit and receive data across a serial port or modem (also known as a COM port), much like a terminal emulation application. Before you can use the control in a program, you must add it to the Toolbox. To do so, right-click in an empty area of the Toolbox, and select Components from the menu. From the Components dialog box, place a check in the box next to Microsoft Comm Control 6.0, and click OK. The control should then appear in your Toolbox.

Next, draw an instance of the control on your form. Note that it always appears as an icon, no matter how large you attempt to draw it.

To set up the MS Comm Control for use with your modem, you need to set these properties:

  • CommPort. An integer that specifies the COM port to which your modem is attached—for example, 2 for COM2.

  • Settings. A string that specifies the baud rate and parity settings.

These two properties can be set at design time or at the beginning of your program in the Load event or Sub Main procedure. If you have a modem on COM3, for example, the statements read as follows:

Form1.MSComm1.CommPort = 3

Form1.MScomm1.Settings = "9600,N,8,1"

Even if you set the CommPort and Settings properties at design time, you still must perform several activities at program startup, namely initializing the communications control and sending the modem a command to turn on Caller ID display. The complete Sub Main procedure from the sample application is shown in Listing 23.1.

Listing 23.1  Initialization Routine for the Caller ID Program

Sub Main()
    Dim nComPort As Integer
    Dim sInit As String
    Dim sTemp As String
    Dim bStop As Boolean

    sINIfile = App.Path & "\CALLID.INI"
    nComPort = CInt(sGetINIString(sINIfile, "General", "ComPort", "2"))
    sInit = sGetINIString(sINIfile, "General", "InitString", "AT#CID=1")

    With frmMain
        'SET UP THE COM PORT
        .MSComm1.CommPort = nComPort
        .MSComm1.Settings = "9600,N,8,1"
        .MSComm1.InputLen = 0

        'OPEN THE CONNECTION AND SEND THE INIT STRING
        .MSComm1.PortOpen = True
        .MSComm1.Output = sInit + Chr$(13)

        'WAIT A FEW SECONDS FOR MODEM RESPONSE
        nTemp = 0
        bStop = False
        While nTemp < 32000 And bStop = False
            nTemp = nTemp + 1
            If .MSComm1.InBufferCount >= 2 Then
                sTemp = .MSComm1.Input
                If InStr(sTemp, sInit) = 0 Then bStop = True
            End If
        Wend

        'IF THE MODEM DIDN'T SAY OK THEN END
        If InStr(sTemp, "OK") = 0 Then
            MsgBox "Modem did not respond with OK.", vbOK + vbCritical, "Error"
            End
        End If
        DoEvents

        'CLEAR REMAINING BUFFER INPUT
        sTemp = .MSComm1.Input

        'START THE TIMER
        .tmrMain.Enabled = True

    End With

    'DISPLAY CALLER INFORMATION FROM LAST TIME
    nCount = CInt(sGetINIString(sINIfile, "General", "CallCount", "0"))
    DisplayList nCount
    frmMain.Show
End Sub

The code in Listing 23.1, which executes only at program startup, demonstrates how to send and receive commands with the modem. Commands are sent to the modem using the MS Comm Control's Output property. (Note that the carriage return is added, just as you would type it.) In other words, if you want to dial a number using the ATDT command, you simply assign the command to the Output property. In Listing 23.1, this property is used to send the initialization string from the INI file to the modem.

If you think back to the process of sending commands to a modem by hand, you may remember that the modem responds with status messages such as OK, or informational messages such as the Caller ID data or a register setting. The MS Comm Control captures these messages and stores them in a buffer. You use the control's Input property to pull information from this buffer into your program, typically by assigning it to a variable. In Listing 23.1, you check the InputBufferLen property to determine whether the control has any data waiting in the buffer. If data is present, you check the data with the Instr function to see whether the modem has responded to the initialization string with OK.

NOTE

The InputLen property controls the number of characters removed from the buffer when you access the Input property. Setting it to zero, as done here, causes every character in the buffer to be returned.

If the modem responds with OK, then you have successfully established communications with it and are ready to begin the process of checking for Caller ID information. To do so, you set the Enabled property of the timer to True, which starts the process. The only remaining item in the Main function is to display the last caller (stored in the INI file) on the form. The procedure DisplayList simply reads the values from the [Call##] section of the INI file and populates the labels on the form.

Checking for Calls

The most important routines in the sample Caller ID program are CheckForCall and WriteCIDData, shown in Listing 23.2. CheckForCall takes care of handling the input from the modem, and WriteCIDData actually parses the Caller ID information into the INI file.

Listing 23.2  Procedures That Parse the Information from the MS Comm Control

Sub CheckForCall()
    Dim nPrevCount As Integer
    Dim l As Long
    Dim sFile As String

    With frmMain
        If .MSComm1.InBufferCount >= 2 Then

            'STOP TIMER AND GET INPUT FROM COM PORT
            .tmrMain.Enabled = False
            sTemp = .MSComm1.Input

            'If input is a small string then ignore
            'It is just the first 'RING' response.
            If Len(sTemp) < 10 Then
                .tmrMain.Enabled = True
                Exit Sub
            End If

            'STORE CALL COUNTER, ADD INFO TO INI FILE
            nPrevCount = nCount
            WriteCIDData (sTemp)

            'IF NO DATA WAS FOUND THEN EXIT
            If nCount = nPrevCount Then
                ClearStuff
                .lbldbName = "No Data Sent " & Now
                Exit Sub
            End If

            'DISPLAY CALLER INFORMATION ON THE FORM,
            'PLAY THE SOUND FILE A COUPLE OF TIMES
            DisplayList nCount

            sTemp = sGetINIString(sINIfile, "Call" & nCount, "Name", "Unknown")
            sFile = sGetINIString(sINIfile, "Sounds", sTemp, "?")
            If sFile <> "?" Then
                l = sndPlaySound(sFile, SND_SYNC)
                l = sndPlaySound(sFile, SND_ASYNC)
            End If
        End If

        'CLEAR ANY EXTRA INPUT FROM THE COMM CONTROL
        sTemp = .MSComm1.Input

        'RESTART TIMER FOR NEXT CALL
        .tmrMain.Enabled = True

    End With

End Sub
Sub WriteCIDData(sInput As String)
    Dim sName As String
    Dim sNumber As String
    Dim sTime As String
    Dim sDate As String
    Dim sSection As String

    'PARSE EACH PIECE OF INFORMATION FROM THE INPUT STRING
    'THIS WILL VARY FROM MODEM TO MODEM (MINE IS A CARDINAL 33.6)

    sNumber = "?"

    If InStr(sInput, "MESG =") Then
        nTemp = InStr(sInput, "MESG =")
        sName = Mid(sInput, nTemp + 7)
        sNumber = "NO NUMBER SENT"
    Else
        nTemp = InStr(sInput, "NMBR =")
        If nTemp <> 0 Then sNumber = Mid(sInput, nTemp + 7, 10)

        nTemp = InStr(sInput, "NAME =")
        If nTemp <> 0 Then sName = Mid(sInput, nTemp + 7)

        nTemp = InStr(sInput, "DATE =")
        If nTemp <> 0 Then sDate = Mid(sInput, nTemp + 7, 4)

        nTemp = InStr(sInput, "TIME =")
        If nTemp <> 0 Then sTime = Mid(sInput, nTemp + 7, 4)

        sTemp = Left$(sNumber, 3) & "-" & Mid$(sNumber, 4, 3) _
                    & "-" & Right$(sNumber, 4)
        sNumber = sTemp
    End If

    If sNumber = "?" Then Exit Sub

    'WRITE INFORMATION TO THE INI FILE

    nCount = nCount + 1
    writeINIString sINIfile, "General", "CallCount", CStr(nCount)

    sSection = "Call" & nCount
    writeINIString sINIfile, sSection, "Time", Format$(Now, "mm/dd hh:mm a/p")
    writeINIString sINIfile, sSection, "Number", sNumber
    writeINIString sINIfile, sSection, "Name", sName
End Sub

The reason you need so many Instr calls is that when you receive information using the MS Comm Control, it comes across as one long string, with embedded carriage returns and line feeds. Notice that WriteCIDData sends the information to the INI file, and then it is read back as separate fields by the CheckForCall function.

NOTE

This project is available at the Web site http://www.mcp.com/info. The project files are contained in the file CALLID.ZIP.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.