VB.NET Dllimport特性內(nèi)容概述
VB.NET的出現(xiàn),為我們帶來了很多新穎的特性。在很大程度上增加了開發(fā)人員的編程效率。在這里我們就一起來體驗(yàn)它的一些特性優(yōu)點(diǎn)。我們可以使用Declare語句調(diào)用外部DLL中的過程。但VB.NET給我們提供了另外一種更加先進(jìn)的----- 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
這樣就可以不任何代碼實(shí)現(xiàn)便可以調(diào)用外部的Dll,即使我們改變方法名為FindwindowA,也可以順利的實(shí)現(xiàn)調(diào)用,因?yàn)槭褂肈llimport特性編譯器可以自動(dòng)追蹤實(shí)際的過程以及方法!#t#
另外,VB.NET Dllimport特性支持幾種可選的參數(shù),來精確定義調(diào)用外部過程的方式,以及外部過程的返回值方式.
CharSet 參數(shù):用于說明字符串傳遞給外部過程的方式,可以是CharSet.Ansi(默認(rèn)),CharSet.Unicode.CharSet.Auto.
ExactSpelling參數(shù):用于指定方法名是否和DLL中的名稱完全一致,默認(rèn)值為True.
EntryPoint參數(shù):用于指定DLL中的實(shí)際函數(shù)名稱.
CallingConvention參數(shù):為入口點(diǎn)指定調(diào)用的約定,值有WinApi(默認(rèn)值),CDecl,FastCallStdCall和ThisCall.
SetLastError參數(shù):判斷被調(diào)用函數(shù)是否設(shè)置了最近一次Win32錯(cuò)誤代碼,如果設(shè)置為True則可以通過Err.LastDllError方法或Marshal.GetLastWin32Error方法讀取這些代碼.
PreServeSig參數(shù):為一個(gè)Boolean值,如果為True ,則將告訴編譯器,方法不應(yīng)被轉(zhuǎn)換為一個(gè)返回HRESULT值函數(shù).
下面使用VB.NET Dllimport特性來調(diào)用myFunction.dll中的名為friend(friend為VB保留名稱)的方法.Dllimport特性帶有Unicode字符串,并影響Win32錯(cuò)誤代碼:
- < 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