Microsoft Computing: Introduction to the Windows API

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

You have probably run into APIs in the past. An API is simply a small program routine that performs a low-level function within a given operating system. OS/400 has a rich library of API routines, giving iSeries programmers access to areas of the system that would otherwise be off-limits.

The same sort of arrangement exists within the Windows operating system. As a Windows programmer, you have access to hundreds of API routines that will allow you to accomplish great things. On the other hand, you could render your PC unbootable through reckless API calls.

The Windows API

The Windows API has been around since cars had wing windows. It's nothing new. The API library originally started under the 16-bit addressing scheme of old and has come along every step of the way with 32-bit Windows and on to 64-bit with Windows Server 2003. In fact, those old 16-bit API routines are still in the library (and consequently complicating the issue a bit, as you'll see.)

The Windows API physically takes the form of three files on your PC: kernel32.dll, gdi32.dll, and user32.dll. The routines contained in kernel32.dll are primarily system-level functions used to control computer resources, perform memory management, etc. The gdi32.dll (Graphics Device Interface) library is used for manipulating graphic objects. The third .dll file--user32.dll--contains the routines that are most likely to be of use to the programmer. In user32.dll reside routines that may open system resources and operating internals to you and allow development of features thought impossible.

The Windows API Calling Convention

Yes, Windows API routines are powerful little bundles of functionality, but there's a price to pay for their use. Since an API routine is external to the program that uses it, the routine must be described to the calling program's compiler, and proper calling convention must be observed.

As a part of the Windows operating system, the API routines are intended to be used with the C or C++ programming languages and use corresponding calling conventions. (Ironically, the C/C++ languages use a calling convention that grew out of Pascal called the "Far Pascal" calling convention.) Well, that's not such a big deal, really. Once you get the hang of it, you'll see that calling a Windows API routine is easier than calling an OS/400 API routine from an RPG IV program.

As an analogy, consider the steps you take to call one iSeries program from another--for example, to call an RPG program from a CL program. When one program calls another, some match-ups must take place. Of course, the program name called must be correct, but beyond that, the parameters passed to the called program must match what the program expects. The number of parameters and their types and lengths must correspond to the parameters expected by the called program.

The same thing holds true for calling a Windows API routine from within another Windows application program. You simply have to match what the external routine expects to be passed to it, and you're off to the races.

Using a Windows API Routine

So how does one use the Windows API? The process requires three steps: identify the proper API routine for the task at hand, declare the external routine to your program, and use the routine in an expression.

Of these three steps, perhaps the most difficult is to identify which API routine to use. The challenge lies in the names of the routines. In many cases, the names of the functions do not seem to have much to do with the services they perform. To help cut the confusion, your best bet is to acquire one of the many fine WinAPI reference books available. A standard reference for the Visual Basic programmer is the Visual Basic Programmer's Guide to the Win32 API by Dan Appleman (ISBN 0672315904). A reference like Dan's lists all of the Win32 API routines by function category together with the parameter types, meanings, and expected output and return values.

For example, suppose you were interested in finding a routine that would retrieve the name associated with the PC your application is running on. A quick look in the index of the Win32 reference under "Computer name" discloses an API routine called GetComputerName, which will return the elusive name.

Once you have a pretty good idea which API routine to use, the next step is to declare the routine to your program (VB6 has been used for the examples shown here). In VB, the declaration of the API is made with the Declare statement placed (where else?) in the general declarations section of a program.

Declare Function GetComputerName Lib "kernel32" Alias _  
  "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long

The statement above describes the external function GetComputerName to the calling program so that when the API is used, the parameters will match.

At first blush, the declare statement may look strange, but there's really not too much to it. The API routine is a function (hence the Function identifier and As Long clause). Being a function means it will return a value--in this case, a long integer--in the course of being run. In many cases, this value is used for a return code signifying the success (non-zero) or failure (zero) of the calling effort.

The routine GetComputerName is part of the "kernel32" library, and it has an alias. An alias is an additional name given to the routine to distinguish it from its 16-bit predecessor. In this example, the real name of the API is GetComputerNameA because GetComputerName--without the "A" on the end--was taken by the old 16-bit version.

The rest of the declare statement refers to the parameters expected by the API. This routine expects two parms: a string variable to put the computer's name into and a size variable that will contain the number of bytes placed in the string. This string-and-length partnering is very common in C-style function calls.

Finally, the API routine must be invoked by using it in a code expression somewhere in your program (Figure 1):

Figure 1: Call an API routine by using it in an expression.

The API GetComputerName is called by using it in the following expression:

lReturn = GetComputerName(myString, lSize)

When the statement is executed, the routine will be invoked to place the name of the computer in myString together with the length of the name in lSize. The return value of 0 or 1 will be placed in the lReturn integer.

Notice how a string and two long integer variables are defined and initialized to accept the result of the API call. The string is given a length of one more than the size to accommodate the null character that so many C-style routines require on the end of a string. Also, the string is filled with 50 bytes of null (hex zeros) before it is passed, which is also a C thing.

Finally, the extra nulls are trimmed from the end of myString, using the lSize value as a guide, and you've got it--the computer's name.

Windows Messaging--How Windows Knows What to Do

Much like OS/400, the Windows OS uses internal messages sent to itself to perform services and to keep track of everything. In fact, a great many of the system functions within Windows are a result of a message being sent and received from one part of the system to another. For example, when you move your mouse around, messages are being generated and dispatched to the various client areas, called windows, that you move the pointer over. Further, the very fact that you have a mouse pointer is a result of messages and the interpretation of those messages.

Windows messages that we might be concerned with are usually sent to a window. Now, you might think you know what a window on the screen is, but you might be surprised by what Windows thinks a window is. Within the operating system, just about every rectangular area that has a distinct identity is a window. For example, buttons, scroll bars, menus, and client areas are all little windows and are capable of sending and receiving messages.

Each little window area can be made to appear to perform a certain function by the Windows OS when a message for that window is received. As an example, the little Close button in the upper right of most screens can be made to look as if it's being pushed down and released, and then the application closes. Windows does all this in reaction to a message sent by the mouse when the cursor is positioned within the boundaries of the button and clicked.

Using the Windows Messaging APIs

It stands to reason that if we are able to send the same sort of message that Windows low-level functions do, we can make Windows do some pretty cool things. As an example of using a messaging API, consider the list box shown in Figure 2.

Figure 2: This is an example of an auto-positioning list box.

This modest form has a list box and a text box, but the real trick is to make the two of them work together. The goal is to get the list box to automatically position itself to show an entry in the list that matches what the user types into the text box. Sure, this can be done with about 12 inches of regular VB code, but there's a better way using, you guessed it, a Windows API.

Again, the hardest part of the process is finding the right API routine for the job. And again, the remedy is to consult a worthy reference. Doing so will lead to discovery of just such an API called SendMessageString.

The SendMessageString API has the ability to send one of those Windows internal messages to one of those Windows internal windows--like a list box. The message is put on a queue and processed by Windows to cause the list box to behave as we require. In this case, we want the list box to search its list of entries for a specific value and return the index of the entry.

Figure 3 displays the declaration of the SendMessageString routine. SendMessageString, when given the appropriate parameter values and sent to a list box, will search the list box and return the index of a given entry. The routine is part of the user32 library, and it takes four parameters.

Figure 3: Here's the SendMessageString API declaration in VB6.

The first parameter, hwnd, is a long integer that is used to identify, to the Windows operating system, the particular window that is to receive the message. This internal task identifier is called a Windows "handle," and every client area has one. The next parameter, wMsg, is the message itself, sent as an integer value. After the message, there are two general-purpose parameters.

SendMessageString is a versatile function that can send a variety of messages to a number of window types. Consequently, the values placed in the parameters will vary. In the case of the list box example in Figure 2, the parameter wParam is the number of the list box entry where the search is to begin, and lParam is the string to search for.

Above the function declaration are a couple of constants that really just represent numeric values (399 and 418.) These constants are done up that way to look like C-style #define statements and to increase readability.

OK, so only one step left: to invoke the SendMessageString API in an expression.

The natural place to put the call to the API is in the text box's Change event, which will fire as each key is typed. Figure 4 shows the code necessary to complete the whole deal.

Figure 4: Call the API routine by referencing it in code.

The list box to be searched is List1, so that's the handle that should be sent to the API (List1.hwnd.) The value 399, masquerading as LB_FINDSTRING, is sent as is a zero to designate that the search should start at the beginning of the list. Finally, the string of text to search for is sent (Text1.Text.)

If successful, the API will return a positive integer. If not, a zero will be returned. The returned value is then used to position the list box with the List1.Selected(lReturn) statement. Figure 2 shows how the list was positioned to "#6 pick up sticks" when the value "#6" was typed in the text box.

The Windows API Is a Powerful Tool

Of course, there are vastly more API routines available--some of them dangerous. At the least, using the Windows API can make short work of a difficult programming task. At best, the API can make something possible that wouldn't be possible without it. Becoming familiar with how the Windows API works and gaining some experience with coding for the API can be a solid programming technique and your friend for years to come.

Chris Peters has 26 years of experience in the IBM midrange and PC platforms. Chris is president of Evergreen Interactive Systems, a software development firm and creators of the iSeries Report Downloader. Chris is the author of The OS/400 and Microsoft Office 2000 Integration Handbook, The AS/400 TCP/IP Handbook, AS/400 Client/Server Programming with Visual Basic, and Peer Networking on the AS/400 (MC Press). He is also a nationally recognized seminar instructor. Chris can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..