1. Introduction

Page 1
I. DECLARING API FUNCTIONS IN VISUAL BASIC

Page 3
1. Introduction
As we mentioned in the Preface, this book is intended for the intermediate or higher Visual Basic programmer and has two goals:
Describe the Win32 API and how to program it from Visual Basic versions 5.0 and 6.0
Describe the basic operation of the Windows NT and Windows 9x operating systems.
It is natural to wonder why a Visual Basic programmer would be interested in using the Win32 API. The simple answer is that the Win32 API functions allow the VB programmer to access the raw power of the Windows operating system.
For better or worse, the Visual Basic programming environment per se attempts to shield the programmer from the full power of the Windows operating system. This is partly because of the added complexity that surrounds operating system programming and partly because of the apparent sense on Microsoft's part that VB programmers need to be protected from these complexities (and thus from making more ''serious" programming errors than are possible in VB).
To get a better feel for the additional power provided by the Win32 API, let's look at some of the simpler things you will learn to do under Visual Basic using the Win32 API:
Add tab stops to a VB list box
Add a horizontal scroll bar to a VB list box
Add a bitmap to a VB menu
Determine whether a VB application is already running and prevent multiple instances of the application

Page 4
Gather system information, such as which version of Windows is running on a system (Windows 95, 98 or NT), the full pathname of the Windows directory, the screen resolution, or the number of buttons on the user's mouse
Add an icon to the Windows System Tray
In addition, you will learn several advanced programming techniques that can be used in your VB applications, such as how to:
Get a list of all running applications
Synchronize two VB applications so that they can work in cooperation with each other (one application pauses while the other completes a task)
Extract data from controls that belong to another application
Subclass windows (and controls) to change their behavior
Install local or global hooks to monitor or alter the behavior of the mouse or keyboard
Inject a DLL into another process space and execute the code in the DLL
Draw using the Windows GDI drawing functions
Install a clipboard viewer to save the results of more than one copy operation for later pasting
Finally, you will learn some of the secrets of how Windows operates, so that you can:
Learn how to map the memory space for a process
Understand the format of executable files, as well as such things as which functions a DLL exports and which DLLs an executable file uses
What Is the Win32 API?
At the present time, Microsoft offers two 32-bit operating systems Windows 98 and Windows NT. The Win32 Application Programming Interface, or Win32 API for short, is the programming interface that is used to programmatically control these operating systems. More specifically, the Win32 API consists of a collection of functions and subroutines that provide programmatic access to the features of the operating system.
Generally speaking, application programming interfaces take the form of a collection of functions (we include subroutines in this generic term) that provide the application's services. The Win32 API is no exception. The Win32 API consists of well over 2,000 functions for performing all sorts of operating system services. Table 1-1 shows some categories of Win32 API functions. This table will give you a good idea of the type of services rendered by the Win32 API.

Page 5
Table 1-1. Some API Function Categories
Bitmap Functions
Message and Message Queue Functions
Brush Functions
Metafile Functions
Clipboard Functions
Mouse Input Functions
Color Functions
Multimedia Functions
Common Dialog Functions
Multiple Display Monitors Functions
Communication Functions
Multiple Document Interface Functions
Coordinate Space and Transformation Functions
Painting and Drawing Functions
Cursor Functions
Path Functions
Data Decompression Library Functions
Power Management Functions
Debugging Functions
Printing and Print Spooler Functions
Device Context Functions
Process and Thread Functions
Dialog Functions
Rectangle Functions
Dynamic Data Exchange Functions
Registry Functions
Dynamic-Link Library Functions
Resource Functions
Error Functions
Scroll Bar Functions
Event Logging Functions
String Manipulation Functions
File Functions
System Information Functions
File System Functions
System Shutdown Functions
Font and Text Functions
Tape Backup Functions
Icon Functions
Time Functions
Keyboard Accelerator Functions
Timer Functions
Keyboard Input Functions
Unicode and Character Set Functions
Large Integer Operations Functions
Window Functions
Line and Curve Functions
Window Station and Desktop Functions
Memory Management Functions
Windows Networking Functions
Menu Functions
 


API Icon Functions
To get an idea of what some of these API functions can do, let's take a quick look at the icon-related functions.
CopyIcon
Makes a copy of an icon
CreateIcon and CreateIconIndirect
Create an icon
CreateIconFromResource
Creates an icon from raw data in a resource file

Page 6
DestroyIcon
Destroys an icon
DrawIcon and DrawIconEx
Draw an icon in a specified location
ExtractIcon, ExtractIconEx, and ExtractAssociatedIcon
Extract icons from an executable file (EXE or DLL)
GetIconInfo
Retrieves information about an icon
LoadIcon
Loads an icon from a specified module or application instance
LookupIconIdFromDirectory and LookupIconIdFromDirectoryEx
Search for an icon that matches certain criteria
Other APIs
Microsoft Windows is not the only application that has an API. For instance, it would be reasonable to say the Microsoft Excel object model is the application programming interface for Excel, and similarly, the Word object model is the API for Microsoft Word, and the Data Access Objects (DAO) object model is the API for the Jet database engine.
Even the PC BIOS and the DOS operating system have APIs. These APIs are used by assembly language programmers to gain programmatic access to the BIOS and DOS services. As you might imagine, the BIOS services are very primitive. For instance, the BIOS has disk services to read a disk sector, write a disk sector and format a disk track. The DOS API services are at a somewhat higher level than the BIOS services and so are generally easier to use. This applies especially to the area of disk access (hence the name Disk Operating System). For instance, the DOS API has functions to open and close a file, read from and write to a file, find a file, delete a file, rename a file, and so on. In short, while the BIOS API understands only disk sectors and tracks, the DOS API understands files.
Windows 9x and Windows NT Two Different Win32 APIs
Anyone who has worked with both Windows 9x and Windows NT knows full well that these are quite different operating systems. They do have very similar user interfaces, but they are quite different underneath the surface.
Aside from the fact that Windows 9x does not support such things as security services and symmetric multiprocessing (using more than one CPU at a time), perhaps the two most significant differences from the API programmer's perspective is that Windows 9x does not support the Unicode character set (except in very

Page 7
limited situations), and it does not protect its own memory from errant applications. As a result, Windows 9x is far less stable than Windows NT.
Curiously, Windows 9x does protect each application's memory from access by other applications, but it does not protect its own memory from access by an application. Therefore, while an errant program cannot corrupt another program, it can corrupt the operating system itself, causing a system-wide crash. On the other hand, Windows NT does protect its own memory from running applications and is thus far less likely to crash as a result of accidental attempts to write to protected memory.
To a casual computer user who does some word processing, keeps checkbook balances on the PC, accesses the Internet, and plays some games, this may not be a major issue. On the other hand, to a serious computer user and especially to a programmer, the more stable the operating system, the less time will be spent waiting for the system to reboot.
For these reasons, I strongly prefer Windows NT. The downside is that Windows NT is less friendly when it comes to some user-interface amenities, and more seriously, it does not have the same breadth of support for hardware devices. Unfortunately, this may be a reason for some to stay away from Windows NT.
In any case, I don't mean to leave the impression that you cannot program successfully in the Windows 9x environment. I did it for many years before switching to Windows NT. It just means that you should expect to get interrupted fairly regularly by system crashes.
Since the two Windows operating systems are so different, it should come as no surprise that each implements the Win32 API differently. Some Win32 API functions are implemented under Windows 9x but not under Windows NT and vice versa. This can make for very awkward coding. For instance, we will need to write two entirely different sets of code to list all of the current processes (running applications) one that works under Windows 9x and one that works under Windows NT.
Fortunately, the documentation usually makes it clear under which operating systems a given API function is supported.
The Obstacles to Win32 API Programming Under Visual Basic
There are two aspects to learning how to use the Win32 API under Visual Basic:
Translating Win32 API functions into the language of Visual Basic so that it can be incorporated into a VB application
Getting an overall sense of the breadth and depth of the Windows API

Page 8
We will try to accomplish both goals. However, this is not a reference book on the Win32 API, so as far as the latter goal is concerned, the emphasis is on the words overall sense. In many respects, the most difficult part of using the Windows API in any language is figuring out whether there is a function that will accomplish a desired goal and just exactly what that function does! This can be a very difficult (and frustrating) challenge since the Win32 documentation is, shall we say, not always written with absolute clarity in mind.
The documentation for the Win32 API, which is now part of the MSDN Library documentation, is written in the language of Visual C++ (although the API documentation per se does not use object-oriented techniques, unlike Microsoft Foundation Classes, or MFC). Accordingly, we will spend considerable time learning to translate Visual C++ function declarations and data type declarations into the language of Visual Basic. When you are done with this book, you should be just about as comfortable reading a VC++ declaration as a VB declaration.
Lest you think that translating the VC++ declarations of Win32 functions into Visual Basic should be a trivial task, note that Win32 uses literally thousands of different "data types" in its function declarations. In order to translate an API function declaration into VB, we must be prepared to replace any of these data types with the dozen or so that VB understands. More seriously, VB treats strings and structures (user-defined types) quite differently than does Win32. Nevertheless, the secret to successful translation is practice, and you will get plenty of that in this book.
Proceed with Circumspection
Of course, the Win32 API is not the only solution to all programming issues. Many tasks can be handled in more than one way. For instance, suppose we (as VB programmers) want to create a text file on the hard disk. We have several choices:
Use the familiar VB Open statement whose complete syntax is:
Open pathname For mode [Access access] [lock] _
As [#] filenumber [Len=reclength]
Take advantage of the new FileSystemObject object model found in the Windows Scripting Runtime Library:
Dim fso As New FileSystemObject
Dim ts As TextStream
Set ts = fso.CreateTextFile("d:\temp\doc.txt", True)
Use the Win32 API CreateFile function, whose rather formidable syntax is:
Private Declare Function CreateFile Lib "kernel32" _
   Alias "CreateFileA" ( _
   ByVal lpFileName As String, _
   ByVal dwDesiredAccess As Long, _

Page 9
   ByVal dwShareMode As Long, _
   ByVal lpSecurityAttributes As Long, _
   ByVal dwCreationDisposition As Long, _
   ByVal dwFlagsAndAttributes As Long, _
   ByVal hTemplateFile As Long _
) As Long
The CreateFile function returns a low-level handle to the file. Of course, using CreateFile only makes sense when it offers some advantages over the other higher-level and much simpler choices. We will see an example of this in Chapter 10, Objects and Their Handles, where we will use the file handle to map a portion of the file directly into an application's virtual memory space.
To create a simple text file, it makes more sense to use one of the simpler, higher-level methods. In fact, the FileSystemObject object uses the CreateFile API function to accomplish its goal, so why not take advantage of that? Indeed, Figure 1-1 shows the API functions that are imported (that is, used by) the file SCRRUN.DLL, which houses the FileSystemObject object. Note that the list includes CreateFileA and CreateFileW, which are the ANSI and Unicode versions of CreateFile. (Incidentally, the program rpiPEInfo shown in Figure 1-1 is one of the applications we will create in this book.)
To be sure, the Win32 API is the lowest level accessible to the programmer (VB or VC++). It allows the VC++-programmer to access the full power of the Windows operating system, and it allows the VB programmer to get much closer to this goal than by using VB alone.
When faced with a programming issue, however, it is generally wise to find the highest-level solution, except perhaps in cases where performance is a serious issue. As you will see as you read this book, there are a great many situations in which the Win32 API is that highest level!
Cautions
Working with the Win32 API is not like working with Visual Basic. With the Win32 API, we are much "closer" to the operating system, and there are far fewer protections than under Visual Basic. Indeed, VB is a very protected environment, for which we pay a penalty in terms of limited access to the operating system itself and very limited direct access to memory.
In particular, when we read or write to memory, we take certain risks (but nothing that a reboot won't fix). If we attempt (either deliberately or inadvertently) to write to or read from protected memory, the operating system will hopefully raise a General Protection Fault, or GPF. Figure 1-2 shows an example of a GPF dialog (under Windows NT 4.0).

Page 10
0010-01.gif
Figure 1-1.
Imports of the scripting runtime library
0010-02.gif
Figure 1-2.
A General Protection Fault
Generally speaking. one of two things will happen when we hit the OK button:
The operating system will abruptly terminate the VB session, but Windows and all other applications will continue to work normally.
The entire system will become unstable, exhibiting some form of idiosyncratic behavior. In this case, we may lose all unsaved data and must reboot the system.

Page 11
I have been programming using Windows API for some time now, under both Windows 95 and Windows NT 4 (but not under Windows 98), and I can tell you from experience that the latter scenario tends to happen much more often under Windows 95 than under Windows NT, which makes perfect sense in view of our earlier discussion about memory protection. In fact, I have very rarely crashed Windows NT (although it has happened a few times).
In any case, this leads me to the single most important maxim for Win32 API programming (or any programming, for that matter):
Save all work in applications, including the VB project, before running any code, especially if it contains API function calls.



WIN32 API Programming with Visual Basic
Win32 API Programming with Visual Basic
ISBN: 1565926315
EAN: 2147483647
Year: 1999
Pages: 31
Authors: Steven Roman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net