在VB编程环境中如果要调用API将需要声明,否则无法使用!
例如我们需要调用系统库中的API来获取计算机的名字,我们先打开API文档说明.查阅到GetComputerName的相关信息如下:
函数原型:
BOOL GetComputerName(LPTSTR lpBuffer, // address of name buffer
LPDWORD nSize // address of size of name buffer
);
参数:
lpBuffer:Points to a buffer to receive the null-terminated character string containing the computer name.
nSize:Points to a variable that specifies the maximum size, in characters, of the buffer. This value should be large enough to contain MAX_COMPUTERNAME_LENGTH + 1 characters.
返回值:
If the function succeeds, the return value is nonzero and the variable represented by the nSize parameter contains the number of characters copied to the destination buffer, not including the terminating null character.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
点击文档后面的Quick Info按钮可以看到库的相关信息:得知该函数需在Win32s以上版本的操作系统中才有.并且该函数存在于Kernel32.lib(C的库文件名,由此可知该函数在Kernel32.dll中)
了解了上述信息后,打开Api Viewer搜索GetComputerName,查到后将它的声明部分复制到程序中如下:
Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
在VB中新建一工程,并放置Command一个
编定如下代码:
Private Sub Command1_Click()
Dim strAs String '定义用来保存计算机名字的字符串
str= String(255, Chr$(0)) '将该字符串用255个空填充
GetComputerName str, 255 '调用Api函数,也可Call GetComputerName(str,255)
str = Left$(str, InStr(1, str, Chr$(0))) '截取返回字串中非空的部分
MsgBox str
End Sub
编译运行该程序在弹出的对话框中出现计算机的名字;