Basic Interop Tutorial - Platform Invoke
Heres your chance to share your own tutorials with the community. Just post them on here. If your lucky they may even be posted on the main site.
1 post
Page 1 of 1
When calling native code in .NET you need to use Platform Invoke. It can be done in two ways with Visual Basic .NET. All examples expect that you have imported System.Runtime.InteropServices
Code: Select all
Both methods work just as fine. But it is also a dynamic way to load functions, this example will minimize the foreground window
Public Declare Function ShowWindow Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nCmdShow As Integer) As Boolean
<DllImport("user32.dll")>
Public Shared Function ShowWindow(ByVal hWnd As IntPtr, ByVal nCmdShow As Integer) As Boolean
End Function
Code: Select all
This covers the basics of PInvoke, but when you start having types not built in in the .NET framework, you need to write them yourself and make sure memory and such is alright. A great resource to find the right way to declare a function is at http://www.pinvoke.netPublic Class Form1
<DllImport("kernel32.dll")> Shared Function LoadLibrary(ByVal lpFileName As String) As IntPtr
End Function
<DllImport("kernel32.dll")> Shared Function FreeLibrary(ByVal hModule As IntPtr) As Boolean
End Function
<DllImport("kernel32.dll")> Shared Function GetProcAddress(ByVal hModule As IntPtr, ByVal lpProcName As String) As IntPtr
End Function
<UnmanagedFunctionPointer(CallingConvention.StdCall)> _
Delegate Function GetForegroundWindow() As IntPtr
<UnmanagedFunctionPointer(CallingConvention.StdCall)> _
Delegate Function ShowWindow(ByVal hWnd As IntPtr, ByVal nCmdShow As Integer) As Boolean
Private Sub HideForegroundWindow()
Dim user32 As IntPtr = LoadLibrary("user32.dll")
Dim GetForegroundWindowAddress As IntPtr = GetProcAddress(user32, "GetForegroundWindow")
Dim ShowWindowAddress As IntPtr = GetProcAddress(user32, "ShowWindow")
Dim GetForegroundWindowInvoker As GetForegroundWindow = Marshal.GetDelegateForFunctionPointer(GetForegroundWindowAddress, GetType(GetForegroundWindow))
Dim ShowWindowInvoker As ShowWindow = Marshal.GetDelegateForFunctionPointer(ShowWindowAddress, GetType(ShowWindow))
Dim ForegroundWindowHandle As IntPtr = GetForegroundWindowInvoker.Invoke()
ShowWindowInvoker.Invoke(ForegroundWindowHandle, 6)
FreeLibrary(user32)
End Sub
End Class
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;
Over 30 projects with source code!
Please give reputation to helpful members!
![Image]()
![Image]()
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;
Over 30 projects with source code!
Please give reputation to helpful members!

1 post
Page 1 of 1
Copyright Information
Copyright © Codenstuff.com 2020 - 2023