VB Api简单入门(2)-一个简单的例子

在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

编译运行该程序在弹出的对话框中出现计算机的名字;



 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值