VB.NET Dllimport相關特點分析
VB.NET編程語言為廣大開發人員帶來了非常大的好處。我們今天就可以通過VB.NET Dllimport特點的介紹來進一步加深對這款語言特點的認知。我們可以使用Declare語句調用外部DLL中的過程。但VB.NET給我們提供了另外一種更加先進的----- Dllimport特性。
如:
- Imports System.Runtime.InteropServices
- < DllImport("user32")> _
- Function Findwindow()Function
Findwindow(ByVal lpClassName As
String, ByVal lpWindowName As
String) As Integer- End Function
- < DllImport("user32")> _
- Function MoveWindow()Function
MoveWindow(ByVal hWnd As String,
ByVal x As Integer, ByVal y As
Integer, ByVal nWidth As Integer,
ByVal nHeight As Integer, ByVal
bRepaint As Integer) As Integer- End Function
- Sub Test()Sub Test()
- Dim hWnd As Integer =
Findwindow(Nothing,
"Untitled-Nodepad")- If hWnd < > 0 Then MoveWindow
(hWnd, 0, 0, 600, 300, 1)- End Sub
這樣就可以不任何代碼實現便可以調用外部的Dll,即使我們改變方法名為FindwindowA,也可以順利的實現調用,因為使用Dllimport特性編譯器可以自動追蹤實際的過程以及方法! #t#
另外,VB.NET Dllimport特性海支持幾種可選的參數,來精確定義調用外部過程的方式,以及外部過程的返回值方式.
CharSet 參數:用于說明字符串傳遞給外部過程的方式,可以是CharSet.Ansi(默認),CharSet.Unicode.CharSet.Auto.
ExactSpelling參數:用于指定方法名是否和DLL中的名稱完全一致,默認值為True.
EntryPoint參數:用于指定DLL中的實際函數名稱.
CallingConvention參數:為入口點指定調用的約定,值有WinApi(默認 值),CDecl,FastCallStdCall和ThisCall.
SetLastError參數:判斷被調用函數是否設置了最近一次Win32錯誤代碼,如果設置為True 則可以通過Err.LastDllError方法或Marshal.GetLastWin32Error方法 讀取這些代碼.
PreServeSig參數:為一個Boolean值,如果為True ,則將告訴編譯器,方法不應被轉換為一 個返回HRESULT值函數.
下面使用VB.NET Dllimport特性來調用myFunction.dll中的名為friend(friend為vb保留名稱)的方法.Dllimport特性帶有Unicode字符串,并影響Win32錯誤代碼:
- < DllImport("myFunction.dll",
EntryPoint:="Friend", CharSet
CharSet:=CharSet.Unicode,
SetLastError:=True)> _- Function MakeFriends(ByVal sl
As String, ByVal s2 As String)
As Integer- End Function
VB.NET Dllimport的特性就為大家介紹到這里。