VB.NET特性----Dllimport特性

王朝c#·作者佚名  2008-05-19
宽屏版  字体: |||超大  

我们可以使用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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有