[
Advertise | Submit Code | About us | Contact us | Link us
]
Go!
Membership Services
Login
Register

Home
C# General

General

C# Language

Design & Architecture

Algorithms

Database

Security

Active Directory

COM Interop

Remoting
C# Windows Forms

General

Combo and List boxes

Miscellaneous Controls

Button Controls

Edit Controls
Cutting Edge

ASP.NET 2.0

Visual Studio 2005

Windows Longhorn

SQL Server 2005
C# Multimedia and GDI+

General

DirectX

GDI+

Audio
Internet & Web

General

Images and multimedia

Database

Utilities

Security

ASP.NET Controls

Design and Architecture

Webservices
.NET

General

Design & Architecture

Algorithms

Database

Security

Active Directory

COM Interop

Remoting

ADO.NET

XML.NET

Tools

Enterprise

IDE
Visual Basic .NET

VB.NET General

VB.NET Controls
General Reading

.NET Books Review

Product Showcase

Book Chapters

Business Design & Strategy
Community

Discuss

Job Board

Discussion

CodeXchange
DeveloperLand

Advertise

Submit Code

About us

Contact us

Link us
Miscellaneous

Favorite Links

Downloads

Programming Sites

Top Stories
Regular Expressions

E-Mail

Date/Time
Home > C# General > General
Win32 API Interop with C#
Posted by on Thursday, September 16, 2004 (EST)

This article shows you how to call Win32 Apis (Application Programming Interface) with C#

This article has been viewed: 11,600 times
Technology: General.

Api.zip (16.18 KB)

Contents

0" />

Top Go to Table of Contents

Introduction

API (Application Programming Interface) is a set of commands, which interfaces the programs with the processors. The most commonly used set of external procedures are those that make up Microsoft Windows itself. The Windows API contains thousands of functions, structures, and constants that you can declare and use in your projects. Those functions are written in the C language, however, so they must be declared before you can use them. The declarations for DLL procedures can become fairly complex. Specifically to C# it is more complex than VB. You can use API viewer tool to get API function declaration but you have to keep in mind the type of parameter which is different in C#.

Most of the advanced languages support API programming. The Microsoft Foundation Class Library (MFC) framework encapsulates a large portion of the Win32 (API). ODBC API Functions are useful for performing fast operations on database. With API your application can request lower-level services to perform on computer's operating system. As API supports thousands of functionality from simple Message Box to Encryption or Remote computing, developers should know how to implement API in their program.

API\’s has many types depending on OS, processor and functionality.

Top Go to Table of Contents

OS specific API

Each operating system has common set of API's and some special

e.g.

Windows NT supports MS-DOS, Win16, Win32, POSIX (Portable Operating System Interface), OS/2 console API and Windows 95 supports MS-DOS, Win16 and Win32 APIs.

Top Go to Table of Contents

Win16 & Win32 API

Win16 is an API created for 16-bit processor and relies on 16 bit values. It has platform independent nature.

e.g. you can tie Win16 programs to MS-DOS feature like TSR programs.

Win32 is an API created for 32-bit processor and relies on 32 bit values. It is portable to any operating system, wide range of processors and platform independent nature.

Win32 API’s has ‘32’ prefix after the library name e.g. KERNEL32, USER32 etc…

All APIs are implemented using 3 Libraries.

-Kernel
-User
-GDI

Top Go to Table of Contents

1. KERNEL

It is the library named KERNEL32.DLL, which supports capabilities that are associated with OS such as

-Process loading.
-Context switching.
-File I/O.
-Memory management.

e.g. The GlobalMemoryStatus function obtains information about the system's current usage of both physical and virtual memory

Top Go to Table of Contents

2. USER

This is the library named "USER32.DLL" in Win32.

This allows managing the entire user interfaces such as

-Windows
-Menus
-Dialog Boxes
-Icons etc.

e.g. The DrawIcon function draws an icon or cursor into the specified device context.

Top Go to Table of Contents

3. GDI (Graphical Device Interface)

This is the library named "GDI32.dll" in Win32. It is Graphic output library. Using GDI Windows draws windows, menus and dialog boxes.

-It can create Graphical Output.
-It can also use for storing graphical images.

e.g. The CreateBitmap function creates a bitmap with the specified width, height, and color format (color planes and bits-per-pixel).

Top Go to Table of Contents

C# and API

Implementing API’s in C# is tuff job for beginners. Before implementing API you should know how to implement structure in C#, type conversion, safe/unsafe code, managed/unmanaged code and lots more.

Before implementing complex API’s we will start with simple MessageBox API. To implement code for MessageBox API open new C# project and add one button. When button gets clicked the code will display Message Box.

Since we are using external library add namespace:

using System.Runtime.InteropServices; 
//Add following lines to declare API>
[DllImport("User32.dll")] 
public static extern int MessageBox(int h, string m, string c, int type); 

WhereDllImport attribute used for calling method from unmanaged code. "User32.dll" indicates library name. DllImport attribute specifies the dll location that contains the implementation of an extern method. The static modifier used to declare a static member, which belongs to the type itself rather than to a specific object, extern is used to indicate that the method is implemented externally. A method that is decorated with the DllImport attribute must have the extern modifier.

MessageBox is function name, which returns int and takes 4 parameters as shown in declaration.

Many API’s uses structure to pass and retrieve values, as it is less expensive. It also uses constant data type for passing constant data and simple data type for passing Built-in data type as seen in previous declaration of MessageBox function.

Add following code for button click event:

protected void button1_Click (object sender, System.EventArgs e)
{
 MessageBox (0,"API Message Box","API Demo",0); 
}
Compile and run project, after clicking on button you will see MessageBox, which you called using API function!!!

Using structure…

Working with API’s, which uses complex structure or structure in structure, is somewhat complex than using simple API. But once you understand the implementation then whole API world is yours.

In next example we will use GetSystemInfo API which returns information about the current system.

First step is open new C# form and add one button on it. Go to code window of form and add namespace:

using System.Runtime.InteropServices; 
//Declare structure, which is parameter of GetSystemInfo. 
[StructLayout(LayoutKind.Sequential)] 
public struct SYSTEM_INFO 
{
 public uint dwOemId;
 public uint dwPageSize;
 public uint lpMinimumApplicationAddress;
 public uint lpMaximumApplicationAddress;
 public uint dwActiveProcessorMask;
 public uint dwNumberOfProcessors;
 public uint dwProcessorType;
 public uint dwAllocationGranularity;
 public uint dwProcessorLevel;
 public uint dwProcessorRevision; 
}
 
//Declare API function
 
[DllImport("kernel32.dll")]
static extern void GetSystemInfo(ref SYSTEM_INFO pSI); 
Where ref is method parameter keyword causes a method to refer to the same variable that was passed into the method.

Add following code in button click event in which first create struct object and then pass it to function.

protected void button1_Click (object sender, System.EventArgs e)
{
 SYSTEM_INFO pSI = new SYSTEM_INFO();
 GetSystemInfo(ref pSI);
 
 //Once you retrieve the structure perform operations on required parameter 
 listBox1.InsertItem (0,pSI.dwActiveProcessorMask.ToString());
}

Top Go to Table of Contents

About Ajit Mungale

Click here if you want to know more about .

Other articles that may interest you

  • Write a Word Add-In – Part 0
  • Write a Word Add-In – Part I
  • Lengthy Operations on Single Thread in .NET Application
  • Learning Draughts
  • Exceptions and Performance
  • Average Rating :

    Discussion Forums
    Got a programming related question? Hopefully someone has the answer... Want to help out other developers? Visit our discussion forums.

    Sponsored by:

    New Articles

  • Exceptions and Performance
    Almost every time exceptions are mentioned in mailing lists and newsgroups, people say they're really expensive.Let's examine that claim, shall we?

  • Creating multilingual websites - Part 1
    Extend the existing globalization capabilities of .NET to create flexible and powerful multilingual web sites. First, create a custom ResourceManager, and then create custom localized-capable server controls to easily deploy multilingual functionality.

  • Parameter passing in C#
    Many people have become fairly confused about how parameters are passed in C#, particularly with regard to reference types. This page should help to clear up some of that confusion

  • Most Popular Articles

  • LDAP, IIS and WinNT Directory Services
    This article explains how to use .NET Directory Services to retrieve and search directory objects, create new directory objects and edit or delete existing directory objects. Describes Active Directory Application Mode (ADAM) and how to use the IIS, WinNT and LDAP directory (ADSI) provider.

  • An in-depth look at WMI and instrumentation, Part II
    WMI stands for Windows Management Instrumentation and, as the name indicates, is about managing your IT infrastructure this article is the second part of a two-part series.

  • An in-depth look at WMI and instrumentation, Part I
    WMI stands for Windows Management Instrumentation and, as the name indicates, is about managing your IT infrastructure this article provides an in-depth look at WMI and MOM 2005

  • New Books

  • Murach's ASP.NET 2.0 Upgrader's Guide: VB Edition
    What’s new and how to use it! That’s what this book delivers if you’re a VB developer who’s interested in upgrading from ASP.NET 1.x to ASP.NET 2.0.

  • C# in easy steps
    Learn to program with Microsoft’s premier programming language. No previous programming knowledge is assumed. With numerous easy-to-follow examples, this title explains the essentials of object-oriented programming with C#.

  • Murach's ASP.NET web programming with VB.NET
    Murach's ASP.NET web programming with VB.NET by Doug Lowe and Anne Prince is a in depth training and reference book for ASP.NET programming using VB.NET. The book builds upon Murach's previous books and covers more advanced concepts for programming ASP.NET pages.

  • Got Code?

    if you have any article , source code , or anything else you'd like to share with this community that you think others might find useful, please submit it here and we will gladly make it available on this site. submit@developerland.com.
    Partners

    All articles are copyrighted by their individual authors unless otherwise specified , everything else Copyright ©2004-2006 DeveloperLand