The essence of VB API programming

Source: Internet
Author: User
Tags exit character set constant copy final functions valid window
The first section of programming: API Basics

The API, in the final analysis, is a series of low-level functions that the system provides to users to access the core of the operating system for advanced programming. You can access the Windows APIs (and other external DLLs) by declaring external procedures in your Visual Basic application. After you declare a procedure, the method that calls it is the same as the procedure that calls Visual Basic itself. To declare a DLL procedure, you need to add a Declare statement in the Declarations section of the Code window, and declare it as a function if the procedure returns a value. For example:

Declare Function publicname Lib "Libname" [alias "Alias"] [[[[ByVal] variable [as type] [, [ByVal] variable [as type]] ...] )] as Type

If the procedure does not return a value, it can be declared as a sub.

By default, a DLL procedure declared in a standard module can be invoked anywhere in the application. DLL procedures defined in other types of modules are private to the module, and must precede them with the private keyword to differentiate. Specifically, the procedure name is case-sensitive in 32-bit Visual Basic. In the previous 16-bit version, this is not case-sensitive, this is where beginners are prone to error.

The LIB clause in the Declare statement is used to tell Visual Basic how to find the DLL file that contains the procedure. If the referenced procedure belongs to the Windows Core Library (User32, Kernel32, or GDI32), you may not include the file name extension. For example:

Declare Function gettickcount Lib "kernel32" Alias "GetTickCount" () as Long. For other DLLs, the LIB clause must specify the path and extension of the file.

If you call a Windows API procedure that uses a string, you must add an alias clause in the declaration statement to specify the correct character set. Windows API functions that contain strings actually have two Gevou ANSI format Unicode formats. Therefore, in the Windows header file, each function that contains a string has both an ANSI version and a Unicode version.

For example, here are two C-language descriptions of the SetWindowText function. As you can see, the first description defines the function as setwindowtexta, and the tail "A" indicates that it is an ANSI function:

Setwindowtexta (HWND hwnd,lpcstr lpstring);

The second description defines it as SETWINDOWTEXTW, and the tail "W" indicates that it is a Unicode function:

SETWINDOWTEXTW (HWND hwnd,lpcwstr lpstring);

Since the actual name of two functions is not "Setwindow Text", you must add an alias clause to refer to the correct function:

Private Declare Function setwindowtext Lib "user32" Alias "Setwindowtexta" (ByVal hwnd as Longg,byval lpstring as String) S Long

Note that the string following the alias clause must be the true name of the procedure and must be case-sensitive. In fact, you just have to remember that only Windows NT supports Unicode format, and Windows 95 only supports ANSI format. As for the difference between the two, it is not necessary to understand the general application development.

VB5 Professional Edition in the VB Directory \winapi subdirectory, with a few files to provide information about the API. The Win32api.txt file contains the structure declarations of the functions and types used in the 32-bit Windows API functions, as well as the values of global constants. The user can use the Add-in "API browser" with VB itself to make the Win32API easy. TXT, as follows:

Click on the menu file item "Load This file ..." select "Win32API" from the WINAPI directory in the VB directory. TXT, you can view the declarations, constant definitions, and data types of the Windows 95 system's API functions. For example, we intend to view the declaration of the function Inverrect (). First, click the "Search" button and enter the string "Inverrect". In the optional column, the blue brightness bar is moved to the Inverrect item. Click the Add button again, and the Inverrect in Visual Basic appears in the selected item. The next step is to click the Copy button, and then switch the window to the Visual Basic development environment, and CTRL + V (paste) where you need to declare the API function.

The declaration method described above is simple, but it can only be done using the API functions of the win dows itself. For Third-party-provided dynamic-link libraries (DLLs) you only have to knock on the keyboard honestly.

Section II: his experiment

Now the reader must be very interested in their own test, the following two examples of practical applications to let you understand the magical use of the API!

1. Keep a form always on top of the screen

We know that VB itself with the function is difficult to complete this function, we can call the Windows API function: SetWindowPos to meet our requirements. Action steps are as follows:

(1) Start the VB5 to create a new project in which a module (Moudel) is added to add a function declaration and a constant declaration portion of the API function as follows in the module, using the API browser above:

' API function declaration

Declare Function setwindowpos Lib "user32" Alias "SetWindowPos" (ByVal hwnd as Long, ByVal hwndinsertafter as Long, ByVal X as long, ByVal y as Long, ByVal CX as Long, ByVal Cy as Long, ByVal wflags as long) as long

' Constant declaration

Global Const Swp_hidewindow = &h80

Global Const swp_noactivate = &h10

Global Const swp_nocopybits = &h100

Global Const swp_nomove = &h2

Global Const Swp_noownerzorder = &h200

Global Const Swp_noredraw = &h8

Global Const swp_noreposition = Swp_noownerzorder

Global Const swp_nosize = &h1

Global Const Swp_nozorder = &h4

Global Const Swp_showwindow = &h40

Global Const Hwnd_bottom = 1

Global Const hwnd_broadcast = &HFFFF&

Global Const hwnd_desktop = 0

Global Const hwnd_notopmost =-2

Global Const hwnd_topmost =-1

Global Const hwnd_top = 0

Global Const flags=swp_nomove Or swp_nosize

The constants that begin with "SWP_" here represent the style that the form has, and these constants can be grouped together by the "OR" operator in VB. A constant that starts with "Hwnd_" represents the position of the form on the desktop. From these constants the meaning of the English words readers should be very easy to understand the style they have. So I don't have to explain. As for why you add these constants instead of anything else, you'll need to check out the Windows SDK Help documentation for this function. Of course this is difficult for beginners, but don't be afraid, as long as you look at the help will slowly understand. Because these API functions are written for C and C + + programmers, it's easy to understand if you know a little C + +.

(2) Now just call the function where you want it to be, and the method called:

Dim Success as Long

Success=setwindowpos (Me.hwnd. Hwnd_topmost,0,0,0,0,flags)

If the value returned by success is not equal to zero, the call succeeds.

For example, if you add two lines of code to a form's Load event, you can achieve the purpose of keeping the form always on top of the screen.

The attentive reader may have found several constants declared in the module declaration in the above example, but why only three? Now you can try changing the second argument in the API function "SetWindowPos" or the items in the constant flags to see what happens to your form?

2. How to VB5 the Win95 in the Ctrl_alt_del, Ctrl_esc, alt_tab three set of hot keys by invoking the API function "SystemParametersInfo" to implement.

First create a new project, add a form and a module to the project, and drag and drop two buttons on the form named "Cmddisable", "cmdenable", and copy the following code into the module:

Public Declare Function SystemParametersInfo Lib "user32" Ahias "SystemParametersInfoA" (ByVal uaction as Long,byval Upara M as long, Lpvparam as Any,byval fuWinIni as Long

Public Const spi_screensaverrunning=97

Copy the following code in the code editing area of the form:

' Make three hot keys fail

Private Sub Cmddisable_click ()


Spi_screensaverrunning,true,byval 1&,0

End Sub

Private Sub form_unload (Cancel as Integer)

' The hot key is valid before the program exits


End Sub

If you combine this feature with a screen saver, your screen saver must be a lot more.

The simple invocation example of an API function is so easy, I believe now that your call to the API is no longer mysterious, then we will look at a more complex application.

Section III: Master Advanced

The above example of a call to the API is just to take you to the Win dows API world to explore. I believe you have explored a little bit and want to achieve something more "fun". Good! Here's a description of an API call that is "fun" and makes your program look more specialized.

Believe that your machine must be equipped with "Kingsoft", try to start it what do you find? It was "gone" after the splash screen. Move the mouse to the lower-right corner of the desktop, which is "hidden" in the Windows tray in the form of an icon. Right-click it also pops up a menu feature item for you to choose from. Now you want to put your own program also to the tray, so that your program has more professional standards!

The following steps are implemented for this feature:

1. The API functions we call here are: "Shell_NotifyIcon", adding the following function declarations and constant declarations in your module:

' The following constants tell the system what is happening on your icon in the Tray

' Constant declaration

Public Const wm_mousemove = &h200 ' Move mouse on icon

Public Const wm_lbuttondown = &h201 ' left mouse button pressed

Public Const Wm_lbuttonup = &h202 ' left mouse button released

Public Const WM_LBUTTONDBLCLK = &h203 ' Double-click the left mouse button

Public Const Wm_rbuttondown = &h204 ' right mouse button pressed

Public Const wm_rbuttonup = &h205 ' right mouse button release

Public Const wm_rbuttondblclk = &h206 ' Double-click the right mouse button

Public Const Wm_sethotkey = &h32 ' responds to your defined hotkey

' API function declaration

Public Declare Function Shell_NotifyIcon Lib "Shell32.dll" Alias "Shell_notifyicona" (ByVal dwmessage as Long, lpdata as Notifyicondata) as Long

' Customize the type ' notifyicondata ' to be used by the calling API Shell_NotifyIcon

Public Type Notifyicondata

Cdsize as Long ' notifyicondata type size

hwnd as Long ' The name handle of your application form

ID number of the uId as Long ' application icon resource

Uflags as Long ' to make those arguments valid it is in the following enumeration type

Combination of ' nif_message, Nif_icon, nif_tip three groups

Ucallbackmessage as Long ' when the mouse moves the form that sends this message to the icon

Hicon as Long ' icon name handle

Sztip as string*64 ' tip text displayed when the mouse is over the icon

End Type

' This is an enumeration type it tells API Shell_NotifyIcon what to do

Public Enum Enm_nim_shell

Nim_add=&h40 ' Add an icon to the Golden disc

Nim_modify=&h1 ' Modify the icon in the gold disc

Nim_delete=&h2 ' Delete the icon in the gold disc

Nif_message=&h1 ' makes the ucallbackmessage in the type ' notifyicondata valid

Nif_icon=&h2 ' makes the hicon in the type ' notifyicondata valid

Nif_tip=&h4 ' makes the sztip in the type ' notifyicondata valid

Wm_mousemove=&h200 ' makes the mouse move message valid

End Enum

' Define a variable of type ' Notifyicondata '

Public Nidprogramdata as Notifyicondata

The above is a type variable for functions and constant declarations and customizations, and here is the invocation method for this API function:

2. On a form, edit a menu item with the following information:

Main Menu: No title, name (MainMenu)

Sub-menu: Title (API programming), name (Submnul);

Title (exit), name (SUBMNU2).

Here just for example, specific features you can edit this menu item according to your specific needs

3. Add the following code to the form's Load event:

Private Sub Form_Load ()

' Hide Form

With Me

. Top =-10000

. Left =-10000

. WindowState = vbminimized

End With

' Set the characteristics of the type Notifyicondata

With Nidprogramdata

. cbsize = Len (nidprogramdata)

. hwnd = Me.hwnd. Uld = vbnull

. uflags = Nif_icon or Nif_tip or nif_message

' Triggers the mouse to move the message

. Ucallbackmessage = Wm_mousemove

. Hicon = Me.icon ' tray ' to put the form icon, you can change the form's icon to your favorite icon

. Sztip = "VB Win32 API Programming" & vbNullChar

End With

' Call the function

Shell_NotifyIcon Nim_add,nidprogramdata

End Sub

' Different actions based on different mouse messages

Private Sub form_mousemove (Button as Inte ger, Shift as Lnteger, x as single, Y as single)

On Error GoTo Form_mousemove_err:

Dim result as Long

Dim msg as Long

' X's value dependency and display mode settings

If Me.scalemode = Vbpixels Then

msg = x


msg = x/screen.twipsperpixe1x

End If

Select Case MSG

Case Wm_lbuttonup

' Here's what you want to do when you add the left mouse button to release


' Here's what you want to do when you double-click the left mouse button.

Case Wm_rbuttonup

' Usually here pops up your menu of features

PopupMenu MainMenu

Case Wm_mouseismoving

' Here's what you want to do when you add the mouse to the move.

End Select

Exit Sub


' Here, add your code to handle the abnormal error.

End Sub

4.Run your program, do you see the same functions as "Kingsoft"? Believe you at this time the feeling must be particularly "cool"!

The world of the API is rich and colorful, as long as you are willing to explore it carefully you will certainly get a lot of unexpected good things. So I think it is worth every person with a "curious" spirit to explore it. Subsequent journals will give readers a detailed introduction to some better and more "Bull" API calls.

I. API programming for the registry

Knowledge of the registry I believe you have a deeper understanding through the introduction of the previous topic. The system has six predefined keywords, which are the entry points for the user or system to access the registry. We use only the first four keywords. In programming, we typically use just the two keywords HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE, because the application-related data exists under these two keywords.

Many commercial software or specialized software on your machine when the first installation will be done by overwriting the registry to complete the correct installation of the software operation, the dream of becoming a master programmer you certainly need to master the technology of reading and writing the registry. Taking advantage of the registry will make your application a lot more beautiful.

Although VB itself provides four functions on the registry getsetting,savesetting, GetAllSettings, deletesetting (these four functions are relatively simple to use the reader can refer to the online help of VB), but these four functions can only be in the " HKEY_CURRENT_USER\Software\VB and VBA programsettings read, delete, and modify key values. Use them for general applications to achieve your purpose, and to use them for special requirements can be very ineffective. Here is an example to illustrate their limitations.

Readers familiar with the DOS operating system know that a "Autoexec.bat" batch file can be written to enable an application to run automatically when the system starts, and in Win95 we can put the application shortcuts to the system's Startup group to achieve the same effect. But what if I need to automatically achieve this effect after my application is first installed? In fact, three such keys are available in the registry:




The difference between these three key words is:

Run: The application under this key word will run automatically when the system is started;

RunOnce: The application under this key will run automatically the next time the system starts, no longer run;

RunServices: As with "Run", it's just different when the application is started.

Now you must know how to use the registration to express your request. In fact, many of the installation software is required to reboot after the Setup Wizard completes to complete the final installation. It is done by writing the final work of the Setup wizard to "RunOnce". However, it is obviously not possible to use the four functions of VB itself. In practice, the author solves the limitation of VB accessing the registry by calling API function, and makes it into a class module. So it's very convenient to call up. Because of the limited space I can only draw a part of it, this part is also able to run independently. Readers want complete source code please contact me (

Here is the declaration section code that should be placed in your module:

Option Explicit

' Registry entry constants

Public Const HKEY_CLASSES_ROOT = &h80000000

Public Const HKEY_CURRENT_USER = &h80000001

Public Const HKEY_LOCAL_MACHINE = &H80000002

Public Const HKEY_USERS = &h80000003

' Registry access constants

Public Const Key_query_value = &h1

Public Const Key_set_value = &h2

Public Const Key_create_sub_key = &h4

Public Const Key_enumerate_sub_keys = &h8

Public Const key_notify = &h10

Public Const Key_create_link = &h20

Public Const key_all_access = &h3f

' Open/Create a key-value optional constant

Public Const reg_option_non_volatile = 0&

Public Const reg_option_volatile = &h1

' Create a new key or open a key constant that already exists

Public Const Reg_created_new_key = &h1

Public Const Reg_opened_existing_key = &h2

' Predefined permissions constants for accessing the registry

Public Const Standard_rights_all = &h1f0000

Public Const Specific_rights_all = &hffff

' Return code constants for API

Public Const error_success = 0&

Public Const error_access_denied = 5

Public Const Error_no_more_items = 259

' Returns a numeric type constant

Public Const Reg_none = (0)

Public Const REG_SZ = (1)

Public Const REG_EXPAND_SZ = (2)

Public Const REG_BINARY = (3)

Public Const REG_DWORD = (4)

Public ConSt Reg_dword_little_endian = (4)

Public Const Reg_dword_big_endian = (5)

Public Const Reg_link = (6)

Public Const REG_MULTI_SZ = (7)

Public Const reg_resource_list = (8)

Public Const Reg_full_resource_descriptor = (9)

Public Const reg_resource_requirements_list = (10)

' The type of structure to use to access the Registry's API functions

Type security_attributes

Nlength as Long

Lpsecuritydescriptor as Long

bInheritHandle as Boolean

End Type


Dwlowdatetime as Long

Dwhighdatetime as Long

End Type

' The API function declaration to use


(In view of the length of this article, we will only introduce the role of each API and no longer one by one columns of its declarations;

The following is a brief introduction to these APIs:

RegOpenKeyEx (): Opens the specified keyword (32-bit);

RegSetValueEx (): Stores data in the domain of the Open registry key;

RegCloseKey (): Frees the handle of the specified keyword;

RegQueryValueEx (): Finds the value associated with the key value you specify in the registry;

RegCreateKeyEx (): Creates and opens the specified keyword, and opens it if it exists;

RegEnumKeyEx (): Enumerates the child keys (32 bits) of the specified open registry key;

Regenumkey (): Ditto function, the difference is that it is 16-bit;

RegEnumValue (): Copies the name and data block of an indexed value each time the value specified by the enumeration is invoked to open the registry key;

Regdeletekey (): Deletes a keyword as well as its sub key word;

Regdeletevalue (): Deletes a value with a name in the specified registry key.

By invoking these APIs we can easily read, query, build, and delete any of the registry's keywords. The author here is only going to introduce how to create and delete a specific keyword. Other operating readers can play by themselves.

For example: To build a "MYAPI" subkey under Hkey_local_machine\network and create a domain called "YX" below it, set its value to "yue1975". We should invoke the API in the following way:

Dim Phkresult as Long ' save established key word handle

Dim Iresult as Long

Dim SA as Security_attributes

Dim 1Create as Long

' Create a specified keyword

Caii RegCreateKeyEx (HKEY_LOCAL_MACHINE, "Network\myapi", 0, "", Reg_option_non_volatile, _


1result=regsetvalueex (Phkresult, "Yx", 0,REG_SZ, "yue1975", Clng (Len ("yue1975") +1)

' Close keyword

RegCloseKey Phkresult

Now use Registry Editor to view the registry, you must have generated the key value you want.

Again for example: Now I want to delete the key value that I just created, then you can just call the following:

Dim success As Long

Success=regdeletekey (HKEY_LOCAL_MACHINE, "NETWORK\MYAPI")

Two. Use API to generate plane tool bar

I believe many VB enthusiasts have made every effort to make their own tool bar like the Word97 in the same cool up. Often we have to borrow other people do a good activebar control, so do not say that their program becomes big, and to tell the truth that the control is not easy to use. The author uses the VC5 programming time to use the base class function Sendmessagelong (), FindWindowEx () to realize this cool effect easily. This inspired the two APIs that were invoked in VB5 to achieve the same effect. The following is the source code:

Add the following program to your module:


' Constant declaration


Public Const Wm_user = &h400

' The starting point for user-defined messages

Public Const Tb_setstyle = Wm_user + 56

' Set toolbar style message

Public Const Tb_getstyle = Wm_user + 57

' Get toolbar style message

Public Const Tbstyle_flat = &h800

' Make the tool bar cool.

Public Const Tbstyle_toolttps = &h100

Public Const tbstyle_wrapable = &h200

Public Const Tbstyle_altdrag = &h400

Public Const tbstyle_list = &h1000

Public Const tbstyle_customerase = &h2000


' API function declaration


Public Declare Function sendmessagelong Lib "user32" Alias "SendMessageA" (ByVal hwnd as Long,

ByVal wmsg as Long,byval WParam as Long,byval 1Param as long) as long

Public Declare Function FindWindowEx Lib "user32" Alias "Findwindowexa" (ByVal hWnd1 as Long,

ByVal HWnd2 as Long,byval 1psz1 as String,byval 1psz2 as String) as Long


' Common generation plane tool bar process

' Entrance: The name of the tool bar


Public Sub Flatbar (ByVal TB as Toolbar)

Dim style as Long

Dim Htoolbar as Long

Dim R as Long

' The tool bar window handle received

Htoolbar = FindWindowEx (Tb.hwnd,0&, "ToolBarWindow32", vbNullString)

' The style of the current tool bar won

style = Sendmessagelong (htoolbar,tb_getstyle,0&, 0&)

If style and Tbstyle_flat Then

style = Style Xor Tbstyle_flat


style = style or Tbstyle_flat

End If

' Set the horizontal style of the tool bar

R=sendmessagelong (htoolbar,tb_setstyle,0, Style)

Tb. Refresh

End Sub

Procedure Flatbar () Method of invocation:

1. Add the Toolbar control (named: MYTB) and the ImageList control to your form. In the usual way, ImageList a few icons in the box and create a common toolbar with toolbar bindings.

2. Call Flatbar () in the form's load () event

Call Flatbar (MYTB)

3. Run, your tool bar must be cool up.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.