談談VB.NET API函數應用
大家都知道VB開發的好處,而且它在Windows環境下越來越多的開發者采用。但如果要開發出專業的Windows軟件,還需采用大量的VB.NET 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的字串變量的大小,函數返回值均為實際目錄的長度。檢查VB.NET API函數如下:
- 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,比較麻煩,VB.NET 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
【編輯推薦】