Wednesday, July 12, 2006

Calling APIs, The .Net Way!

What is Windows API?

The Windows API is the name given by Microsoft to the core set of application programming interfaces available in the Microsoft Windows operating systems. It is designed for usage by C/C++ programs and is the most direct way to interact with a Windows system for software applications.

The functionality provided by the Windows API can be grouped into various categories like Base Services, Graphics Device Interface, User Interface, Common Dialog Box Library, Common Control Library, Windows Shell, Network Services.

The .Net Way!

Now we will see how to call an API function in .Net. As we all know that .Net supports Interop Services, its very easy to call an API function using the namespace "System.Runtime.InteropServices".

Before going to the coding section, lets start with an example. Here I am going to use Windows API for hiding the mouse cursor and showing it back. For this purpose, I am going to use the API user32.ShowCursor function which is under the category User Interface.

Let us start the coding by first including the namespace "System.Runtime.InteropServices". This namespace provides a wide variety of members that support COM interop and platform invoke services.

using System.Runtime.InteropServices;

Then comes the declaration part. Here we declare the API function that we are going to use. Here we have to specify the dll to which the function refers. In our case it is User32.dll.

static extern int ShowCursor(bool bShow);

The Statement DllImport is an attribute which you use to define platform invoke methods for accessing unmanaged APIs. This definition should be made inside the main class like other member functions and variables.

The interesting part is calling the API function. It is very straight forward. Just use the following statement.

ShowCursor(false); // Hide cursor

ShowCursor(true); // Show cursor

Some Tips...

For beginners, implementing APIs is a tough job. There is a quick reference website ( which provides the structure and sample code (sometimes) for all the APIs. But first you need to know which API function is needed for your use. You can find it easily by searching in Google. Happy Coding!


Roi said...

I started messing with api today and this site could save me few hours of hunting down examples.

Writing Articles said...

I find this information very useful and it has considerably saved my time.thanks

Buy Articles