Calling Win32 APIs from the .NET Framework - The Easy Way

Although the .NET Framework contains a comprehensive catalog of classes that encapsulate much of the operating system, real-world applications often need to go beyond the Base Class Libraries and interact directly with the underlying Win32 APIs, either because a managed class doesn't exist for the required method or because it doesn't go far enough. If you're integrating deeply with the shell, want to interact with other windows, or just want to use a service such as fax or RAS, then you'll be getting to know the vagaries of Platform Invoke, the technology which allows you to cross the managed / unmanaged boundary.

The problem is that declaring external functions to be accessed via P/Invoke is a somewhat arcane science, with pitfalls ranging from string mutability to struct layout. Adam Nathan has written a brilliant book that acts as a comprehensive reference to P/Invoke and COM interop, but its sheer size can be daunting for someone who just needs to make a couple of simple calls.

I was pleased therefore to be reminded in a recent email thread of the existence of PInvoke.NET, a wiki that provides sample code for many of the external signature declarations you might need. It comes with C# and VB samples, along with documentation or example code for the majority of well-used calls. Check out the User32, Gdi32 and Kernel32 sections for the majority of the Win32 APIs, or simply search for the API function you're looking for. Lastly, there's even a Visual Studio Add-in so you don't even need to leave the comfort of your IDE to take advantage of the interop help given. The site is a little weak on navigation - it would be nice if there was more "discoverability" of the various APIs so that you didn't need to know in advance what you were looking for, but it's a valuable asset to any VB or C# developer's toolbox.