COM Interoperability in .NET Part 1

The .NET Code

Let us progress to how to call Win32 MessageBox() function from a C# class using PInvoke.

namespace APIExample
{
  using System;
  // Must refernce this library to use PI nvoke types
  using System.Runtime.InteropServices;
  public class PinvokeClient
  {
    [DllImport("user32")]
    public static extern int MessageBox(int hWnd,
    String pText ,
    String pCaption ,
    int uType);

    public static int Main(string[] args)
    {
      String pText = "HELLO INDIA!!";
      String pCaption = "Example by Arungg";
      MessageBox(0,pText,pCaption,0);
      return 0;
    }
  }
}

Before calling a C-style Dll we have to declare the function to call using the static and extern C# keywords. After this you have to specify the name of the raw DLL that contain the function you are attempting to call,as shown here.

[DllImport("user32")]
public static extern int MessageBox(.......);

After declare the DLL Pass the arguments such as pText,pCaption.It should be clear that it does not matter in which order you specify the values.
In the above way one can use .Net types calling any type of raw C DLLs (Win32 API).This comes to an end of Part1 and I think the users now know how to call a raw C DLLs (Win32 API) using PInvoke in .NET.

You might also like...

Comments

About the author

G.Gnana Arun Ganesh

G.Gnana Arun Ganesh India

G.Gnana Arun Ganesh is the Administrator and the Founder of ARUN MICRO SYSTEMS (www.arunmicrosystems.netfirms.com). He has been programming in C++, Visual Basic, COM, Java and Microsoft Technolo...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.”