Using The Win32 API - Visual Basic 6 (VB6)
Using The Win32 API - Visual Basic 6 (VB6)
Ads b Google VB6 Code MSDN for VB6 API SmartCard VB6
Search
Contents
Introduction What is the API and why should I use it? Declaring API Functions A little C goes a long way with the API. Calling API Functions Many, if not most, API procedures require you to prepare the variables provided before you make the actual call. Rules for API Programming The API is not without its hazards, but if you follow a few simple guidelines you can safely use VB's greatest addon. Summary
Introduction
The Win32 Application Programming Interface (API) is probably the most powerful add-on component available for Visual Basic. Hundreds of functions are available to perform a wide variety of tasks. Unfortunately, many Visual Basic programmers do not take advantage of these powerful functions - often because of tales they may have heard of complexity, general protection faults, and other nasty but unfounded problems.
2/22/12
to perform common windows tasks, such as creating and destroying windows, controls, and menus; accessing system services such as the display, keyboard and mouse input, and printing; and many other functions. Functions in the API are provided in several files known as Dynamic Link Libraries (DLLs). The DLLs in the Win32 API export, or make public, many of their functions which can then be called by any Windows application.
Declare template for Function procedures: [ bi P lc Piae DcaeFn innm Lb"inm"[la "lanm" [[rls]][ tp] ] el c o ae i lbae Ai aisae] (agit) A e
Let's look at each of the components of these statements. Pbi o Piae lc r This is a standard VB scope modifier. Declare statements must be placed in the declarations section of a module (they cannot appear within a procedure), and the Public or Private keyword determines if the procedure is available throughout the application or only within the module in which it is declared. N R API D DcaeSbo DcaeFn in el r el c o This indicates whether or not the procedure returns a value.
www.vb6.us/tutorials/using-win32-api 2/10
2/22/12
:Y V V B )I B
, .
nm ae This is the name of the function N :S .H . Lb"inm" i lbae The Lib is the name of the library (DLL) where the function is located. N :T D .T . , . . API ,(
API
(rls) agit This is a standard Visual Basic argument list. It indicates what parameters are expected by the procedure, the data types of the parameters, and whether they are passed ByVal or ByRef. N G T W VB .W . A tp e Used only for functions, this specifies the data type of the return value. This may be a little easier to illustrate with an example. The following is the Declare statement for the FindWindow function. FindWindow returns a window handle given the window's title bar text or classname. PiaeDcaeFnto FnWno Lb"sr2 Ais"ididw"(_ rvt elr ucin ididw i ue3" la FnWnoA BVllCasaeA Srn,_ ya plsNm s tig BVllWnoNm A Srn)A Ln ya pidwae s tig s og Let's look at each component of this declare: Private The function is declared as Private to the module. This is because a wrapper function for the API call is provided elsewhere in the module, so the Private Declare statement ensures that only the wrapper will be called directly. Function FindWindow This procedure returns a value (a window handle). Lib "user32" Alias "FindWindowA" The procedure is exported from the user32 library, where it can be found as FindWindowA. N :T W 32 API ANSI , ANSI U "A" . .F VB, . API , , As An A A VB : GPF .
ByVal lpClassName As String, ByVal lpWindowName As String The function takes two parameters, both ByVal strings. As Long The function returns a long integer value. The FindWindow function also illustrates another common API feature: redundant parameters. FindWindow will accept a window title and a window classname, but either by itself is enough to get a window handle returned (assuming of course that such a window exists). However, to avoid needing to provide two separate functions that serve essentially the same purpose, the API has constructed the function so that either or both values can be supplied. If you only want to supply one of them (and in most cases you will), simply pass a binary zero for the other
www.vb6.us/tutorials/using-win32-api 3/10
2/22/12
parameter. To pass binary zero (a null in C lingo, but not to be confused with a VB Null which is something else entirely), you can either enter ByVal 0& as the parameter value or use the intrinsic constant vbNullString.
2/22/12
null-terminated string to the API. Any variable which will be modified by the function is passed ByRef. Structures (VB types) are always passed as addresses. D ' API .Y ' , ). , , .A API ( ' - ' , .I API V ' ,
2/22/12
Es le 'tefnto fie,hnl i hr h ucin ald ade t ee EdI n f Prior to calling the function, 256 is assigned to nSize and the sBuffer string is assigned 256 spaces. (As far as I know, 256 is way more than enough characters for a legal computer name on any windows platform. The heavily padded buffer may be slightly sloppy coding, but for this purpose we're not worried about wasting a few dozen bytes in a local procedure. Once the parameters have been setup, the API function is called and the result is tested. If the value of lResult is non-zero (indicating success), then two things will be true: 1. The computer name will have been placed into the sBuffer string. 2. The nSize variable will contain the length of the computer name in sBuffer, not including the null terminator. At this point, it's a simple matter of using the Left$() function to extract everything to the left of the terminating null. Functions that return a size in the parameter list in this manner will nearly always return the required size if the buffer was too small to hold the result. You can use this information to test for a large enough buffer by comparing the value returned to the original value you provided. You can also use the "double-calling" technique, where you call once with a buffer that's known to be too small, the using the return values to allocate a buffer that's just large enough to hold the required result. Unless the procedure is in the middle of a tight loop, there's rarely a measurable performance penalty for using the double-calling method. Similarly, many functions will return string sizes as the function return value. Again, these functions will typically provide the required size if the buffer was too small to hold the result. Finally, some API functions are just plain lazy and tell you nothing at all about the size of the returned string. In these cases, you can use the InStr() function to search for the position of the first null character (use vbNullChar) and then use Left$() to extract everything to the left of the null.
Wa ning
DON'T MISMATCH THE SIZE YOU SEND AS PARAMETER WITH THE ACTUAL SIZE OF THE BUFFER! Yes, I'm shouting, and for good reason. The Win32 API expects you to do what you said you're going to do. If you tell it you provided a buffer of a given size, it will write up to that number of characters at the address provided. Consider what would happen if you did this: DmsufrA Srn i Bfe s tig DmnieA Ln i Sz s og DmleutA Ln i Rsl s og nie=24 Sz 08 sufr=Sae28 Bfe pc(4) leut=Gtoptraesufr nie Rsl eCmueNm(Bfe, Sz) If we assume for the moment that this function could return a string as long as the value of nSize, we would be in for some serious trouble. We've told the function that we're supplying a 2048 byte buffer, but in fact only allocated 248 bytes. If the function found 2048 bytes of characters to return, it would write over whatever happened to be in memory following the first 248 bytes of the string we sent. This could be other program data, program code, anything at all. If you're really, really lucky, Windows will abruptly terminate your application with a General Protection Fault. Unfortunately, it may well be the case that your application will run merrily along, having corrupted it's own code or data in some random location. This may manifest itself as strange behavior or data elsewhere, random crashes at unrelated locations, and all other sorts of nearly impossible to debug problems.
www.vb6.us/tutorials/using-win32-api 6/10
2/22/12
Summar
This page, like nearly every other I've ever seen on programming the API, has a few scare tactics in it. Before you shy away from the API, however, keep in mind that it's not nearly as difficult as it looks and in most cases is no harder than coding straight VB functions. The API is a powerful tool, but is intended for use by grown-ups. By this I don't mean veteran programmers, just programmers that are thorough and accurate in their coding. If you have sloppy programming habits, doing things like naming your variables "Jane" and "Spot", ignoring return values to save the line of code it takes to test them, not paying attention to ByVal or ByRef passing, then you should clean up your act before you inflict total instability on your users by adding API programming (compared to the near total instability you'll have using those habits without the API). If, however, you're willing to write a little bit of simple code and use a little bit of good judgement, the API can be the greatest add-on component available to you - and it's available for the cost of just a few lines of code. By Joe Garrick
www.vb6.us/tutorials/using-win32-api
7/10
2/22/12
PDF Wri er for VB www.s nactis.com Create, displa , print, edit, merge Ro alt -free distribution. Tr now!
Similar links
Subclassing in VB6 ActiveX Tutorial Understanding the Windows API in VB Rectangular and Circular Collision Detection Using the FlashWindow API to get the users attention Creating Advanced PDF documents in VB Creating PDF files in Visual Basic Convert C Strings to VB Strings Activate Any Window With API Access Security Using Jet Data Access Objects 31342 reads
There is an error in the GetComputerName code. it uses "nSize" where in fact "lSize" is necessary. These lines are
www.vb6.us/tutorials/using-win32-api
8/10
2/22/12
thks. reply
Homepage:
Subject:
Comment: *
Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> Lines and paragraphs break automatically.
Preview
Unless otherwise noted, all content on this site and in the source samples is Copyrighted 2011 by the owner of vb6.us. All rights reserved - Contact Information
www.vb6.us/tutorials/using-win32-api 9/10
2/22/12
www.vb6.us/tutorials/using-win32-api
10/10