中國最大的web開發資源網站及技術社區,
我們可以使用declare語句調用外部dll中的過程。但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特性編譯器可以自動追蹤實際的過程以及方法!
 另外,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值函數.
 
 
 下面使用dllimport特性來調用myfunction.dll中的名為friend(friend為vb保留名稱)的方法.dllimport特性帶有unicode字符串,并影響win32錯誤代碼:
 
<dllimport("myfunction.dll", entrypoint:="friend", charset:=charset.unicode, setlasterror:=true)> _
 function makefriends(byval sl as string, byval s2 as string) as integer
 
 end function