Saturday, February 2, 2008

Access the Win32 API in .NET

Windows exposes lots of functionality in the form of Win32 API. Using these API you can perform direct operation in windows, which increases performance of your application.API is a set of predefined Windows functions used to control the appearance and behavior of every Windows element. Every user action causes the execution of several or more API function telling Windows what's happened.
  • using System.Runtime.InteropServices;
In .NET we can call Win 32 API using platform Interop Services, which resides at System.Runtime.InteropServices namespace, Which is useful when you are interacting with external application.

  • [DllImport("User32.dll")]

This statement will import the user32.dll in your program after that you can make use of its function in your program.

  • public static extern Int32 FindWindow(String lpClassName,String lpWindowName);

Before 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.

eg: FindWindow, EnumChildWindows, EnumWindows, ..etc


This is example, I have done sample Console application in .NET. Here you can see message box with "
Hello World!".Windows functions used to control the appearance and behavior of every Windows element like as massage box.

using System;
using System.Runtime.InteropServices;


namespace ConsoleApplication1
{
class Program
{
// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

static void Main()
{
// Call the MessageBox function using platform invoke.
MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
}
}
}







No comments: