现在的位置: 首页 > 综合 > 正文

DllImport用法

2013年10月11日 ⁄ 综合 ⁄ 共 1804字 ⁄ 字号 评论关闭

DllImport用法
  DllImport 作为一种属性提供第二种方法调用不带类型库的 DLL 中的函数。DllImport 大致与使用 Declare 语句等效,但对如何调用函数提供更多的控制。
  可以将大多数 Windows API 调用与 DllImport 一起使用,只要该调用引用的是共享(有时称为“静态”)方法就可以。不能使用需要类实例的方法。与 Declare 语句不同,DllImport 调用不能使用 MarshalAs 属性。
  使用 DllImport 属性调用 Windows API
  通过在“文件”菜单上单击“新建”,然后单击“项目”,打开一个新的“Windows 应用程序”项目。出现“新建项目”对话框。
  从 Visual Basic 项目模板的列表中选择“Windows 应用程序”。将显示新项目。
  将一个名为 Button2 的按钮添加到启动窗体上。
  双击 Button2 打开窗体的代码视图。
  要简化对 DllImport 的访问,请向启动窗口类的代码顶部添加一条 Imports 语句:
  Visual Basic  复制代码
  Imports System.Runtime.InteropServices
  在 End Class 语句之前为窗体声明一个空函数,并将函数命名为 MoveFile。
  将 Public 和 Shared 修饰符应用到函数声明中,并基于 Windows API 函数使用的参数来设置 MoveFile 的参数:
  Visual Basic  复制代码
  Public Shared Function MoveFile( _
  ByVal src As String, _
  ByVal dst As String) _
  As Boolean
  ' Leave the body of the function empty.
  End Function
  函数可以有任意一个有效的过程名;DllImport 属性指定 DLL 中的名称。它还为参数和返回值处理互操作封送处理,因此可以选择与 API 使用的数据类型相似的 Visual Studio 数据类型。
  将 DllImport 属性应用到空函数中。第一个参数是包含要调用的函数的 DLL 的名称和位置。不必为位于 Windows 系统目录下的文件指定路径。第二个参数是一个命名参数,指定 Windows API 中的函数名称。在本示例中,DllImport 属性强制将 MoveFile 调用转发给 KERNEL32.DLL 中的 MoveFileW。MoveFileW 方法将文件从路径 src 复制到路径 dst。
  Visual Basic  复制代码
  <DllImport("KERNEL32.DLL", EntryPoint:="MoveFileW", SetLastError:=True, _
  CharSet:=CharSet.Unicode, ExactSpelling:=True, _
  CallingConvention:=CallingConvention.StdCall)> _
  Public Shared Function MoveFile( _
  ByVal src As String, _
  ByVal dst As String) _
  As Boolean
  ' Leave the body of the function empty.
  End Function
  将代码添加到 Button2_Click 事件处理程序,以调用函数:
  Visual Basic  复制代码
  Private Sub Button2_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles Button2.Click
  Dim RetVal As Boolean = MoveFile("c:/tmp/Test.txt", "c:/Test.txt")
  If RetVal = True Then
  MsgBox("The file was moved successfully.")
  Else
  MsgBox("The file could not be moved.")
  End If
  End Sub
  创建名为 Test.Txt 的文件并将其放在您硬盘的 C:/Tmp 目录下。如果有必要,可创建 Tmp 目录。
  按 F5 键启动该应用程序。将显示主窗体。
  单击“Button2”。若文件可以移动,则显示“The file was moved successfully”。

 

抱歉!评论已关闭.