API函數在VB開發中的應用
VB作為快速開發Windows下的編程工具,已經為越來越多的開發者采用。但如果要開發出專業的Windows軟件,還需采用大量的API函數,以下結合筆者開發管理軟件的經驗談幾點體會。
1.程序中判定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 |
2.程序中判斷Windows的安裝目錄
一般VB開發出來的程序包含vbrun300.dll等輔助文件和.vbx文件,它們均需安裝到Windows目錄(c:windows)或Windows的系統目錄(c:windowssystem)下,但因為用戶安裝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:WINDOWSSYSTEM" Then checkdir = False Exit Function End If checkdir = True End Function |