vb.net 动态调用api

复制代码
Imports System
Imports System.Runtime.InteropServices

Public Class DllInvoke
    Public Sub New(ByVal DLLPath As String)
        Me.hLib = DllInvoke.LoadLibrary(DLLPath)
    End Sub

    Protected Overrides Sub Finalize()
        Try
            DllInvoke.FreeLibrary(Me.hLib)
        Finally
            MyBase.Finalize()
        End Try
    End Sub

    <DllImport("kernel32.dll")> _
    Private Shared Function FreeLibrary(ByVal [lib] As IntPtr) As Boolean
    End Function

    <DllImport("kernel32.dll")> _
    Private Shared Function GetProcAddress(ByVal [lib] As IntPtr, ByVal funcName As String) As IntPtr
    End Function

    Public Function Invoke(ByVal APIName As String, ByVal t As Type) As [Delegate]
        Return Marshal.GetDelegateForFunctionPointer(DllInvoke.GetProcAddress(Me.hLib, APIName), t)
    End Function

    <DllImport("kernel32.dll")> _
    Private Shared Function LoadLibrary(ByVal path As String) As IntPtr
    End Function

    Private hLib As IntPtr
End Class
复制代码

 

复制代码
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Text

Public Class test

    Private Declare Function MessageBoxA Lib "user32" Alias "MessageBoxA" (ByVal hwnd As Integer, ByVal lpText As StringBuilder, ByVal lpCaption As StringBuilder, ByVal wType As Integer) As Long
    Private Delegate Function MessageBoxADelegate(ByVal hwnd As Integer, ByVal lpText As StringBuilder, ByVal lpCaption As StringBuilder, ByVal wType As Integer) As Long

    Public Shared Sub Main()
        Dim invoke As New DllInvoke("user32.dll")
        Dim mode As MessageBoxADelegate = DirectCast(invoke.Invoke("MessageBoxA", GetType(MessageBoxADelegate)), MessageBoxADelegate)
        mode.Invoke(0, New StringBuilder("haha"), New StringBuilder("title"), 0)
        Console.WriteLine("ok")
        Console.ReadLine()
    End Sub
End Class
复制代码

posted on   空明流光  阅读(2083)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示