如何:调用采用无符号类型的 Windows 函数 (Visual Basic)

如果使用具有无符号整数类型成员的类、模块或结构,则可以使用 Visual Basic 访问这些成员。

调用采用无符号类型的 Windows 函数

  1. 使用 Declare 语句 告诉 Visual Basic 哪个库保存函数、该库的名称、调用序列是什么,以及如何在调用函数时转换字符串。

  2. Declare 语句中,根据每个具有无符号类型的参数的需要,使用 UIntegerULongUShortByte

  3. 请参阅要调用的 Windows 函数的文档,查找它使用的常量的名称和值。 其中许多是在 WinUser.h 文件中定义的。

  4. 在代码中声明必要的常量。 许多 Windows 常量是 32 位无符号值,应声明这些 As UInteger值。

  5. 以正常方式调用函数。 以下示例调用 Windows 函数,该函数 MessageBox采用无符号整数参数。

    Public Class windowsMessage
        Private Declare Auto Function mb Lib "user32.dll" Alias "MessageBox" (
            ByVal hWnd As Integer,
            ByVal lpText As String,
            ByVal lpCaption As String,
            ByVal uType As UInteger) As Integer
        Private Const MB_OK As UInteger = 0
        Private Const MB_ICONEXCLAMATION As UInteger = &H30
        Private Const IDOK As UInteger = 1
        Private Const IDCLOSE As UInteger = 8
        Private Const c As UInteger = MB_OK Or MB_ICONEXCLAMATION
        Public Function messageThroughWindows() As String
            Dim r As Integer = mb(0, "Click OK if you see this!",
                "Windows API call", c)
            Dim s As String = "Windows API MessageBox returned " &
                 CStr(r)& vbCrLf & "(IDOK = " & CStr(IDOK) &
                 ", IDCLOSE = " & CStr(IDCLOSE) & ")"
            Return s
        End Function
    End Class
    

    可以使用以下代码测试函数 messageThroughWindows

    Public Sub consumeWindowsMessage()
        Dim w As New windowsMessage
        w.messageThroughWindows()
    End Sub
    

    谨慎

    UIntegerULongUShortSByte 数据类型不属于语言独立性和 Language-Independent 组件(CLS),因此符合 CLS 的代码无法使用这些数据类型。

    重要

    调用非托管代码(例如 Windows 应用程序编程接口 (API))会使代码面临潜在的安全风险。

    重要

    调用 Windows API 需要非托管代码权限,这可能会影响其在部分信任情况下的执行。 有关详细信息,请参阅 SecurityPermission代码访问权限

另请参阅