VB.NET Dllimport特性內容概述
VB.NET的出現,為我們帶來了很多新穎的特性。在很大程度上增加了開發人員的編程效率。在這里我們就一起來體驗它的一些特性優點。我們可以使用Declare語句調用外部DLL中的過程。但VB.NET給我們提供了另外一種更加先進的----- VB.NET Dllimport特性。
如:
- Imports System.Runtime.
InteropServices- < DllImport("user32")> _
- Function Findwindow(ByVal
lpClassName As String, ByVal
lpWindowName As String) As Integer- End Function
- < DllImport("user32")> _
- 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()
- 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