VB's API programming essence

xiaoxiao2021-03-06  108

Section 1: API foundation

The API said that the bottom is a series of underlying functions, and the system is provided to the user to enter the operating system core, and advanced programming. Windows APIs can be accessed by declaring external processes in the Visual Basic application. After declaring the process, the method calling it is the same as the process of calling Visual Basic. To declare a DLL process, you need to add a declare statement in the "Declaration" section of the code window. If the process returns a value, it should be declared as function. E.g:

Declare function publicname lib "libname" [alias "alias"] [([Byval] variable [as type] [, [byval] variable [as type]] ...)] as Type

If the process does not return a value, it can be declared as SUB.

By default, the DLL process declared in the standard module can call anywhere in the application. The DLL process defined in other types of modules is the module private, and must be added to the private keyword to show the distinction. Try to note that the process names in 32-bit Visual Basic are case sensitive. In the previous 16th versions, it is not case sensitive, which is a place where beginners are easy to make mistakes.

The lib clause in the DECLARE statement is used to tell Visual Basic how to find a DLL file that contains the process. If the referenced process belongs to the Windows core library (User32, Kernel32 or GDI32), the file extension can be not included. E.g:

Declare function gettickcount lib "kernel32" alias "gettickcount" () as long. For other DLLs, the lib clarion must specify the path and extension of the file.

If the calling Windows API process is used to use a string, you must add an Alias ​​clause in the declaration statement to specify the correct character set. A Windows API function containing strings, there are two Genu ANSI formats Unicode format. Therefore, in the Windows header file, each function containing a string has an ANSI version and Unicode version.

For example, the following is two C language describing the setWindowText function. It can be seen that the first description defines the function as setWindowTexta, the "A" of the tail indicates that it is an ANSI function:

SetwindowTexta (HWND HWND, LPCSTR LPSTRING);

The second description defines it as setWindowTextw, "W" at the end indicates that it is a Unicode function:

SetwindowTextw (HWND HWND, LPCWSTR LPSTRING);

Because the actual names of the two functions are not "setWindow text", you must add an Alias ​​clause to the correct function:

Private Declare Function SetWindowText Lib "User32" Alias ​​"SetWindowTexta" (Byval LPSTRING AS STRING) AS Long

Note that the string behind the Alias ​​clause must be the true name of the process, must be case sensitive. In fact, you only need 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 for general application development. VB5 Professional Edition provides information about the API with several files in a VB directory / WinAPI subdirectory. The win32api.txt file contains a 32-bit Windows API functionality declaration and a value of the global constant. Users can easily use Win32API using the external program "API browser" with the VB itself. TXT, as shown below:

Click on "Loading Text File ..." from the WINAPI directory of the menu file item to select "Win32API.txt", you can view the declaration, constant definition and data type of the API function of the Windows 95 system. For example, we intend to view the declaration of the function inverRect (). First, click the "Search" button to enter the string "InverRect". In the Optional bar, the brightness of the blue light will move on the "InverRect" item. Press the "Add" button again, "InverRect" declaration in Visual Basic appears in "Selection". Next, you will naturally click the "Copy" button and then switch the window to the Visual Basic development environment, which is required to declare the API function. Ctrl V (Paste).

Although the declaration method mentioned above is simple, only the API function using Win Dows itself can be like this. For a third-party dynamic link library (DLL) you only knock on the use of keyboards.

Section 2: Cow knife

Now readers must really want to try themselves. The following examples will give you two practical applications, let everyone know how the API!

1. Always keep a form on the top of the screen

We know that the VB itself comes with a function that is difficult to complete this feature, we can call our requirements by calling Windows: SetWindowPos reaches our request. The steps are as follows:

(1) Start VB5 to establish a new project, add a module (moudel) in this project, and add the function declaration and constant declaration of the API function to the "API Exist" described 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 statement

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 = & h8global 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

Here, the constant beginning with "SWP_" is a style indicating the form, which can be combined with the "OR" operator in VB. The constant starting with "hwnd_" represents the location of the form on the desktop. In the sense of English words from these constants, the reader should be able to understand the style they have. Therefore, the author will not explain it. As for why you want to add these constants instead of this, you want to go to see the help documentation for the Windows SDK about the function. Of course, there is a certain difficulty for beginners, but don't fear, just want to take care of it carefully. Because these API functions are written for C and C , it is easy to understand if you know a little C .

(2) Now you can call this function when you want this feature, the method of calling is:

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

For example, add the two lines of code described above in a LOAD event in a form, you can reach the top of the screen at the top of the screen.

The careful readers may have discovered that the modules in the above example declare several constants, but why only use three? Now you can try to change the second parameter or constant Flags in the API function "SetWindowPOS", see what effect appears in your form?

2. How to block the Ctrl_Alt_Del, Ctrl_esc, and Alt_Tab, Alt_Tab, Alt_Tab, Alt_Tab, Alt_Tab, and Alt_Tab, Alt_Tab, and Alt_Tab.

First create a new project; add a form and a module in this project; drag and drop two buttons on the form, name "cmddisable", "cmdenable"; COPY is in the following code into the module:

Public Declare Function SystemParametersInfo Lib "User32" AHIAS "SystemParametersInfoa" (Byval Upram As Long, LPVParam As Any, BYVAL Fuwinini As Long) AS Long

Public const spi_screensaverrunning = 97

In the code editing area COPY as follows:

'Failure of three sets of hot bonds

Private subddisable_click () SystemParametersInfo

SPI_Screensaverrunning, True, Byval 1 &, 0

End Sub

Private Sub Form_Unload (Cancel AS Integer)

The hotkey is effective before the program exits.

CNDENABLE_CLICK

End Sub

If you combine this function and the screen saver, then your screen saver has a lot of color.

The simple call example of the API function is so easy. I believe that you now call the API's call no longer feel mysterious. Let's take a look at a more complex application.

Section III: Master advanced

The above example of the call to the API is just to take you to the WIN DOWS API world to explore. I believe that you have explored a little eyebrow and want to achieve something more "fun". it is good! Let you introduce you to a very "fun" at the same below, will make your program look more professional an API call.

I believe that there must be "Jinshan Word" on your machine, try to start it you found? It was "gone" after the startup screen. Move the mouse to the lower right corner of the desktop, "hidden in" Windows tray "in the form of an icon. Right click in the mouse to pop up a menu function item for you to choose. Now you have to put your own procedure to the tray so your program has a professional level!

Below is the implementation step of this feature:

1. Here we call the API function is: "shell_notifyicon", add the following function declaration and constant declaration in your module:

'The following constants tell the system what happened on your icon in your icon.

'Constant statement

Public const wm_mousemove = & h200 'Move mouse on the icon

Public const wm_lbuttondown = & h201 'mouse left mouse button

Public const wm_lbuttonup = & h202 'mouse left mouse button release

Public const wm_lbuttondblclk = & h203 'Double-click the left mouse button

Public const wm_rbuttondown = & h204 'mouse button

Public const wm_rbuttonup = & h205 'mouse button to release

Public const WM_RBUTTONDBLCLK = & H206 'Double-click Mouse button

Public const wm_sethotkey = & h32 'Responding to your defined hotkey

'API function declaration

Public Declare Function Shell_Notifyicon Lib "Shell32.dll" Alias ​​"shell_notifyecona" (Byval DwMessage As Long, LPData As Notifyicondata) As long

'Customize a call API shell_notifyicon to use the type "Notifyicondata"

Public Type Notifyicondata

Cdsize as long 'notifyiicondata type size

HWND as long 'your application form

Uid as long 'application icon resources ID number

UFlags as long 'makes those parameters it is in the following enumeration type

Combination of 'nif_message, nif_icon, nif_tip

UCALLBACKMESSAGE AS Long 'Mouse moves this message to the form of the icon Hicon as long' icon

SZTIP AS STRING * 64 'When the mouse is displayed on the icon, the Tip text is displayed.

End Type

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

Public Enum ENM_NIM_SHELL

NIM_ADD = & H40 'Add a icon in "Gold Disc"

NIM_MODIFY = & H1 'Modify the icon in "Gold Disc"

NIM_DELETE = & H2 'Delete icons in "Gold Disc"

Nif_Message = & H1 'makes UcallbackMessage in the type "Notifyicondata" valid

Nif_icon = & h2 'enables HiCon in the type "Notifyicondata" effective

Nif_tip = & h4 'makes SZTIP in the type "Notifyicondata" effective

WM_MOUSEMOVE = & H200 'makes the mouse move message is valid

END ENUM

'Define a variable of a "notifyicondata" type

Public NidprogramData as Notifyicondata

The above is a function and constant statement and a custom type variable, the lower side is the call method of this API function:

2. Edit a menu item with the following information on the form:

Main menu: No title, Name (Mainmenu)

Sub-menu: Title (API Programming), Submnul;

Title (exit), name (Submnu2).

Here is just an example, the specific function you can edit this menu item according to your specific needs.

3. Add the following code in the form of the LOAD event:

Private sub flow_load ()

'Hiding form

WITH ME

.Top = -10000

.Left = -10000

.Windowstate = vbminimized

End with

'Set the feature of type Notifyicondata

With nidprogramdata

.cbsize = len (NidProgramData)

.hwnd = me.hwnd .uld = vbnull

.uflags = nif_icon or nif_tip or nif_message

'Trigger mouse movement message

.ugallbackMessage = WM_MOUSEMOVE

.hicon = me.icon '"Tray" is placed in the form icon, you can change the form of the form to the icon you like

.sztip = "Win32 API programming" & vbnullchar

End with

'Call this function

Shell_Notifyicon Nim_Add, NidprogramData

End Sub

'Different operations according to 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 value dependent and display mode settings

If me.scalemode = vbpixels then

MSG = X

Else

Msg = x / screen.twipsperpixe1x

END IF

SELECT CASE MSG

Case WM_LButtonup

'Add the left mouse button here to release the operation you want to do

Case WM_LBUTTONDBLCLK

'Add to do the left click here to do what you want to do

Case WM_RBUTTONUP

'Usually pop up your function menu

Popupmenu mainmenu

Case WM_Mouseismoving

'Join the mouse here when you are moving, you want to do it.

End SELECT

EXIT SUB

FORM_MOUSEMOVE_ERR:

'Add your code here for abnormal errors

End Sub

4.Run Your program, do you see the same function like "Jinshan Words"? I believe that you feel very particularly "cool" at this time!

The world J of the API is colorful. As long as you are willing to explore it, you will have a lot of unexpected things. Therefore, the author feels that it is worth having a "curious" spirit to explore it. Subsequent Journalists will introduce some "cattle" API calls to readers.

1. API programming of the registry

Knowledge regarding the registry believes that you have a deeper understanding through the introduction of the previous topic. The system has six predefined keywords, which is the entry point of the user or system access to the registry. We often use only the first four keywords. When programming, we generally use only two keywords that are just hkey_current_user and hkey_local_machine, because data related to the application exists in both keywords.

Many commercial software or specialized software will complete the software's correct installation and run by rewriting the registry to the registry, and dreams you have to master the technique of the programming. Use a good registry to have a lot of color to your application.

Although VB itself provides four functions of the registry GetSetting, Savesetting, getAllSettings, deletesetting (more simple readers can refer to the VB online help), but these four functions can only be "HKEY_CURRENT_USER / SOFTWARE / Read, delete, modify the key value under VB and VBA ProgramSettings. For general applications, you can use them to achieve your goal, and use them to use them for a special requirement. Here, an example will be given to illustrate their limitations.

Readers who are familiar with the DOS operating system know that the batch file of "Autoexec.bat" can be written to implement an application automatically run when the system is started. In Win95, we can put the application's shortcut to the system. The same effect is achieved in the launch group. However, if I need to automatically reach this effect after my application is installed, what should I do? In fact, three such keys are available in the registry:

HKEY_LOCAL_MACHINE / SOFTWARE / Microsoft / Windows / CurrentVersion / RUN

HKEY_LOCAL_MACHINE / SOFTWARE / Microsoft / Windows / CurrentVersion / RunOnce

HKEY_LOCAL_MACHINE / SOFTWARE / Microsoft / Windows / CurrentVersion / RunServices

The difference between these three keys is:

Run: This key is automatically run when the application is started;

Runonce: This key is automatically run when the system is started next time, and it will not be run in the future;

RunServices: Functions and "run", only when the application is started.

Now you know how to use the registry to meet your requirements. In fact, many installation software wants you to restart after the installation wizard is completed to complete the final installation. It is implemented by writing the last job required by the installation wizard to "runonce". However, if only the four functions of the VB itself is obviously unable to implement this feature. The author solves the limitations of the VB itself accessed by calling the API function in practice, and makes it a class module. So it is very convenient to call. Since the space is limited, I can only draw some from it, this part can also run independently. Readers want a complete source code, please contact me (Yue_xiang@263.net). Here is the declaration section of the declaration in your module:

Option expedition

'Entrance constant of the registry

Public const hkey_classes_root = & h80000000

Public const hkey_current_user = & h80000001

Public const hkey_local_machine = & h80000002

Public const hkey_users = & h80000003

'Access permission constant of the registry

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

'Option constant for opening / establishing key values

Public const rag_option_non_volatile = 0 &

Public const rag_option_volatile = & h1

'Establish a new key or open the existing key

Public const rag_created_new_key = & h1

Public constreg_opened_existing_key = & h2

'Pre-defined access registry permissions constant

Public const standard_rights_all = & h1f0000

Public const specific_rights_all = & hffff

'API return code constant

Public const error_success = 0 &

Public const error_access_denied = 5

Public const error_no_more_items = 259

'Return numeric type constant

Public const rag_none = (0)

Public const rag_sz = (1)

Public const rag_expand_sz = (2)

Public const rag_binary = (3)

Public const rag_dword = (4)

Public const rag_dword_little_endian = (4)

Public const rag_dword_big_endian = (5)

Public const rag_link = (6)

Public const rag_multi_sz = (7)

Public const ram_resource_list = (8) public const reg_full_resource_descriptor = (9)

Public const rag_resource_requirements_list = (10)

'Access the structure type of the API function to the registry

Type Security_Attributes

NLENGTH AS Long

LPSecurityDescriptor as long

BinheritHandle As Boolean

End Type

Type filetime

DwlowDatetime As Long

DWHighDatetime As Long

End Type

'The API function declaration to use

..........

(In view of the difference here only introduces the role of each API, no one is listed in the statement; related statement, please check the API browser)

Let's take a brief introduction to these APIs:

RegopenKeyex (): Open the specified keyword (32-bit);

RegSetValueex (): Stores data in the value domain of the open registry keyword;

RegcloseKey (): Release the handle of the specified keyword;

RegQueryValueex (): Find values ​​related to the key value you specify in the registry;

RegreateKeyex (): Create and open the specified keyword, if you already exist, turn it;

RegenumKeyex (): Enumerates the specified sub-key (32-bit) that opens the registry keyword;

RegenumKey (): Like the same function, the difference is that it is 16-bit;

RegenumValue (): Each time you call an enumerated value to open the registry keyword, copy a name and data block with an indexed value;

RegdeleteKey (): Delete a keyword and its sub-keyword;

RegdeleteValue (): Delete a value with name in the specified registry keyword.

By calling these APIs we can easily implement the read, query, establishment, deletion of any keywords for the registry. The author only intends to introduce how to establish and delete a specific keyword. Other operating readers can play themselves.

For example: To build a "MyApi" subkey in HKEY_LOCAL_MACHINE / NETWORK and establish a value domain called "YX" below it, set it to "Yue1975". We should call the API as follows:

DIM PhkResult As long 'Save the created keyword handle

DIM IRESULT AS Long

Dim Sa as security_attributes

Dim 1CREATE AS Long

'Establish a specified keyword

CAII RegcreateKeyex (HKEY_LOCAL_MACHINE, "NetWork / MyAPi", 0, "", REG_OPTION_NON_VOLATILE, _

Key_All_access, SA, PhkResult, 1CREATE

1Result = RegSetValueex (PhkResult, "YX", 0, Reg_SZ, "YUE1975", CLNG (Len ("Yue1975") 1))

'Close keyword

RegcloseKey PhkResult

Now use the Registry Editor to view the registry, you must generate the key values ​​you need.

Another example: Now I want to delete the key value I have just created, then you only need to call as follows:

DIM SUCCESS AS Long

Success = regdeletekey (HKEY_LOCAL_MACHINE, "NetWork / MyApi") II. Generate a flat toolbar with API

I believe that many VB enthusiasts have tried to make their tools in Word97, as COOL. Often we have to borrow an ActiveBar control to use others, so you don't say your own procedure becomes big, and that the control is not easy to use. The author uses the base class function SendMessagelong () when programming with VC5, and FindWindowEx () is easy to implement this Cool effect. Inspired by this inspiration, these two APIs are called in VB5 and also achieve the same effect. Here is the source code:

Put the following procedures to your module:

'----------------------

'Constant statement

'----------------------

Public const wm_user = & h400

'The starting point of user custom message

Public const tb_setStyle = WM_USER 56

'Setting the tool strip style message

Public const tb_getStyle = WM_USER 57

'Get tool strips

Public const twstyle_flat = & h800

'Enable tool bar Cool

Public const twstyle_toolttps = & h100

Public const twstyle_wrapable = & h200

Public const tbstyle_altdrag = & h400

Public const twstyle_list = & h1000

Public const tbstyle_customrase = & h2000

'-----------------

'API function declaration

'-----------------

Public Declare Function SendMessagelong Lib "User32" Alias ​​"SendMessagea" (Byval Hwnd As Long,

Byval WMSG 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

'-----------------------

'Universal generating plane toolbar process

'Entrance: The name of the toolbar

'-----------------------

Public Sub Flatbar (Byval TB As Toolbar)

DIM STYLE AS Long

DIM HTOOLBAR AS Long

DIM R As Long

'Waiting tool bar window handle

HToolbar = FindWindowEx (TB.hwnd, 0 &, "ToolbarWindow32", VBnullString)

'The style of the current toolbar

Style = SendMessagelong (Htoolbar, TB_GetStyle, 0 &, 0 &)

If Style and TBStyle_Flat Then

Style = style xor tbstyle_flat

ElseStyle = Style or TBStyle_flat

END IF

'Set the flat style of the toolbar

R = SendMessagelong (HToolbar, Tb_setStyle, 0, Style)

TB.Refresh

End Sub

Procedure FLATBAR () Call Method:

1. Add a Toolbar control (named: myTB) and ImageList controls on your form. In the usual method, in ImageList, a few icons and Toolbar bind to Toolbar build a usual toolbar.

2. Tune flatbar () in the form () event of the form.

Call flatbar (MyTB)

3. Run, your toolbar must be Cool.

转载请注明原文地址:https://www.9cbs.com/read-97745.html

New Post(0)