Home > Articles > Programming > Visual Basic

Master's Toolbox

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020