Basic interop tutorial - C#

All tutorials created in C# to be posted in here.
2 posts Page 1 of 1
Contributors
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

Basic interop tutorial - C#
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
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
User avatar
DreadNought
VIP - Donator
VIP - Donator
Posts: 116
Joined: Fri Jan 08, 2010 12:37 pm

Re: Basic interop tutorial - C#
DreadNought
Nicely done, should go into changing window names since your using the same imports(I think? cant remember)
Bound and boom tech,
The Future Of Coding
2 posts Page 1 of 1
Return to “C-Sharp Tutorials”