我们可以使用 Declare语句调用外部DLL中的过程。但VB.NET给我们提供了另外一种更加先进的----- Dllimport特性。
如:
Imports System.Runtime.InteropServices
1<dllimport("user32")> _
2
3Function Findwindow( ByVal lpClassName As String , ByVal lpWindowName As String ) As Integer
4
5End Function
6
7<dllimport("user32")> _
8
9Function 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
10
11End Function
12
13Sub Test()
14
15Dim hWnd As Integer = Findwindow( Nothing , "Untitled-Nodepad")
16
17If hWnd <> 0 Then MoveWindow(hWnd, 0, 0, 600, 300, 1)
18
19End Sub
20
21这样就可以不任何代码实现便可以调用外部的Dll,即使我们改变方法名为FindwindowA,也可以顺利的实现调用,因为使用Dllimport特性编译器可以自动追踪实际的过程以及方法!
22
23另外,Dllimport特性海支持几种可选的参数,来精确定义调用外部过程的方式,以及外部过程的返回值方式.
24
25CharSet 参数:用于说明字符串传递给外部过程的方式,可以是CharSet.Ansi(默认),CharSet.Unicode.CharSet.Auto.
26
27ExactSpelling参数:用于指定方法名是否和DLL中的名称完全一致,默认值为True.
28
29EntryPoint参数:用于指定DLL中的实际函数名称.
30
31CallingConvention参数:为入口点指定调用的约定,值有WinApi(默认 值),CDecl,FastCallStdCall和ThisCall.
32
33SetLastError参数:判断被调用函数是否设置了最近一次Win32错误代码,如果设置为True 则可以通过Err.LastDllError方法或Marshal.GetLastWin32Error方法 读取这些代码.
34
35PreServeSig参数:为一个Boolean值,如果为True ,则将告诉编译器,方法不应被转换为一 个返回HRESULT值函数.
36
37下面使用Dllimport特性来调用myFunction.dll中的名为friend(friend为vb保留名称)的方法.Dllimport特性带有Unicode字符串,并影响Win32错误代码:
38
39<dllimport("myfunction.dll", )="" ,="" charset:="CharSet.Unicode," entrypoint:="Friend" setlasterror:="True"> _
40
41Function MakeFriends( ByVal sl As String , ByVal s2 As String ) As Integer
42
43End Function</dllimport("myfunction.dll",></dllimport("user32")></dllimport("user32")>