Wednesday, May 11, 2005

Calling Win32 API in .net

Win32 API (Application Programming Interface) is a set of dlls, basically, predefined Windows functions used to control the appearance and behavior of every Windows element. Most commonly used ones are User32.dll, Kernel32.dll, Gdi32.dll, Comdlg32.dll etc... In .NET world it is UnManaged Code.In .NET we can call Win 32 API using platform Interop (P-Invoke) Services, which resides at System.Runtime.InteropServices namespace

Windows API calls were an important part of any programming model. Whenever possible, you should use managed code from the .NET Framework to perform tasks instead of Windows API calls. Before going through the trouble of and exposing yourself to the risk of calling Win32 APIs directly, make sure that the functionality you require is not already available in .NET. Some system event, for examples, can be accessed through the Microsoft.Win32 Namespace. Other functions are now an integral part of the .NET object model. That said, if you really do need to call the Win32 API, there are a few things to keep in mind:

Windows dynamic-link libraries (DLLs) represent a special category of interoperability. As mentioned earlier, Windows APIs do not use managed code, do not have built-in type libraries, and use data types that are different than those used with Visual Studio .NET. Because of these differences, and because Windows APIs are not COM objects, interoperability with Windows APIs and the .NET Platform is performed using platform invoke, or PInvoke. Platform invoke is a service that enables managed code to call unmanaged functions implemented in DLLs.

You can use PInvoke by applying the DllImport attribute to an empty procedure.
In C#, For example

public class Win32
{
[DllImport("User32.dll")]
public static extern Int32 FindWindow(String lpClassName,String lpWindowName);
}

For using any external function in .NET you have to declare that function in your program. In above statement we are trying to use FindWindow function of User32.dll. While declaring such a function we prefix extern keyword with that, which indicate that the declared function is an external function.

Some Good Artciles
Consuming Unmanaged DLL Functions

.NET Interoperability: .NET ↔ Win32

Working with Win32 API in .NET

Microsoft Win32 to Microsoft .NET Framework API Map

.NET interop marshaling made easier

Calling Windows APIs

Platform Invocation Services in .NET Framework

PINVOKE.NET

A Win32 Library for .NET

Hope that was intresting

0 Comments:

Post a Comment

<< Home