Basic interop tutorial - C#
Posted: Thu Mar 01, 2012 2:09 pm
When calling native code in .NET you need to use Platform Invoke. This is one way to do it with CSharp .NET.
Code: Select all
It is also a dynamic way to load functions, this example will minimize the foreground window
[DllImport("user32.dll")]
public static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
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 or structure is at http://www.pinvoke.netusing System.Runtime.InteropServices;
public class Form1
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr GetForegroundWindow();
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate bool ShowWindow(IntPtr hWnd, int nCmdShow);
private void HideForegroundWindow()
{
IntPtr user32 = LoadLibrary("user32.dll");
IntPtr GetForegroundWindowAddress = GetProcAddress(user32, "GetForegroundWindow");
IntPtr ShowWindowAddress = GetProcAddress(user32, "ShowWindow");
GetForegroundWindow GetForegroundWindowInvoker = Marshal.GetDelegateForFunctionPointer(GetForegroundWindowAddress, typeof(GetForegroundWindow));
ShowWindow ShowWindowInvoker = Marshal.GetDelegateForFunctionPointer(ShowWindowAddress, typeof(ShowWindow));
IntPtr ForegroundWindowHandle = GetForegroundWindowInvoker.Invoke();
ShowWindowInvoker.Invoke(ForegroundWindowHandle, 6);
FreeLibrary(user32);
}
}