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.

Comments (2)

  1. Anonymous says:

    I like, which I used recently to access the API functions for changing the computer name. However, when I tried to get the signatures using the plugin, it didn’t find anything. I went to the website and searched for it and found what I needed. So if you use the plugin, don’t be deterred by a not found. Go to the website and check for it.

  2. Anonymous says:

    I love PInvoke.Net but it list of signatures is incomplete (missing CBT_CREATEWND among others). It would very helpful if a few people from MS took the time to update the site with more signatures. From what I read someone inside MS has written a tool which parses header files and spits correctly declared structs. If this was done for all the Win32 and releated headers, then I’m sure there would enough interested volunteers to update PInvoke.NET.
    <br>In addition when I went to roll my own struct definitions I found little documentation about what some of the types corresponded to.

Skip to main content