Page 1 of 1

Basic interop tutorial - C#

Posted: Thu Mar 01, 2012 2:09 pm
by MrAksel
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
[DllImport("user32.dll")]
public static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
It is also a dynamic way to load functions, this example will minimize the foreground window
Code: Select all
using 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);
	}

}
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.net

Re: Basic interop tutorial - C#

Posted: Sat Mar 24, 2012 1:43 am
by DreadNought
Nicely done, should go into changing window names since your using the same imports(I think? cant remember)