VB 程序设计

10个成员

API函数在VB开发中的应用

发表于 2016-12-21 2642 次查看
   VB作为快速开发Windows下的编程工具,已经为越来越多的开发者采用。但如果要开发出专业的Windows软件,还需采用大量的API函数,以下结合笔者开发管理软件的经验谈几点体会。
   程序中判定Windows的版本
   众所周知,Windows3.x各版本或多或少会有些差别,为了使开发程序避免出现莫名其妙的错误,最好在程序运行前自动判定Windows的版本。采用API提供的函数getversion很容易实现这一点。函数声明如下:
Declare Function GetVersion Lib"Kernel"() As Integer
   此函数没有参数,返回值为Windows的版本号,其中版本号的低位字节为Windows的主版本号,版本号的高位字节返回Windows的次版本号。判别过程如下:
Private Sub Form_Load ()
Dim ver As Integer
Dim major As Integer
Dim minor As Integer
Ver = GetVersion ()
major = ver And &HFF
minor = (ver And &HFF00) \ 256
If major <> 3 And minor <> 10 Then
MsgBox "版本不正确!"
Exit Sub
End If
End Sub
   程序中判断Windows的安装目录
   一般VB开发出来的程序包含vbrun300.dll等辅助文件和.vbx文件,它们均需安装到Windows目录(c:\windows)或Windows的系统目录(c:\windows\system)下,但因为用户安装Windows时可能会改变Windows的目录名(如c:\windows),使用安装软件后,不能正确运行.API中提供的GetwinDowsdirectory或GetSystemDirectory较好地解决了这个问题。函数声明如下:

Declare Function GetSystemDirectory Lib "Kernel"(ByVal lpBuffer As
String,ByVal nSize As Integer) As Integer

   其中参数lpbuffer为字串变量,将返回实际Windows目录或Windows的系统目录,nsize为lpbuffer的字串变量的大小,函数返回值均为实际目录的长度。检查函数如下:

Function checkdir() As Boolean
Dim windir As String * 200
Dim winsys As String * 200
Dim winl As Integer
Dim wins As Integer
Dim s1 As String
Dim s2 As String
winl = GetWindowsDirectory(windir,200)
winl = GetSystemDirectory(winsys,200)
s1 = Mid $(windir,1,winl)
s2 = Mid $(winsys,1,wins)
If Wins = 0 Or wins = 0 Then
checkdir = False
Exit Function
End If
If s1 <> "C:\WINDOWS" Or s2 <> "C:\WINDOWS\SYSTEM" Then
checkdir = False
Exit Function
End If
checkdir = True
End Function

shell 出现的问题
   通常编程时要调用外部程序,VB提供了shell()函数,但是如果shell调用的外部程序找不到,则运行的程序失去控制,VB给出提示"filenotfound",改变这种现象,要在程序中加入onerrorgoto,比较麻烦,API函数中的winexec很好地解决了这个问题。函数声明如下:

Declare Function WinExec Lib "Kernel"(ByVal lpCmdLine As String,
ByVal nCmdShow As Integer) As Integer

   其中lpCmdline为调用的外部文件名,NcmdShow为外部程序的运行状态,如隐藏窗口、最小化窗口等等。如返回值大于32表示执行功能,否则返回错误码。例程如下:

sub command1_click
ds i as integer
i=winexec("notepad.exe","c:\wst.txt",9)
'参数9 即SW_RESTORE,也就是激活并显示窗口
if i>32 then
msgbox "调用正确!!"
else
msgbox "调用错误!!"
end if
end sub

 

发表回复
你还没有登录,请先登录注册