21
Sat, Dec
3 New Articles

Microsoft Computing: Introduction to the Windows API

Microsoft
Typography
  • 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):

http://www.mcpressonline.com/articles/images/2002/Microsoft-WindowsAPI%20March%202004%20V300.jpg

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.


http://www.mcpressonline.com/articles/images/2002/Microsoft-WindowsAPI%20March%202004%20V301.jpg

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.

http://www.mcpressonline.com/articles/images/2002/Microsoft-WindowsAPI%20March%202004%20V302.jpg

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.

http://www.mcpressonline.com/articles/images/2002/Microsoft-WindowsAPI%20March%202004%20V303.jpg

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..

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: