Click here to Skip to main content
Click here to Skip to main content

Calling API functions using C#

, 10 Oct 2001
Rate this:
Please Sign up or sign in to vote.
This article helps you to get an idea about calling API functions in C#.
<!-- Download Links --> <!-- Article image -->

Sample Image - usingAPI.gif

<!-- Add the rest of your HTML here -->

Introduction

An 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 pieces functionality from simple nessage boxes to encryption or remote computing; developers should know how to implement the API in their program.

APIs have many types depending on OS, processor and functionality.

OS specific API:

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

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.

Win16 & Win32 API:

Win16 is an API created for 16-bit processor and relies on 16 bit values. It has a 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, a wide range of processors and is of a platform independent nature.

Win32 APIs has the '32' prefix after the library name e.g. KERNEL32, USER32 etc -

All APIs are implemented using 3 Libraries.

  • Kernel
  • User
  • GDI

1. KERNEL

It is the library named KERNEL32.DLL, which supports capabilities that are associated with the 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

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.

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

C# and API:

Implementing APIs in C# is a tough 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 APIs we will start with simple MessageBox API. To implement code for the MessageBox API open a new C# project and add one button. When button gets clicked the code will display a Message Box.

Since we are using external library, add a namespace:

using System.Runtime.InteropServices;

Add the following lines to declare the API

[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);

Here the DllImport attribute is used for calling the method from unmanaged code. "User32.dll" indicates the library name. The DllImport attribute specifies the dll location that contains the implementation of an extern method. The static modifier is 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 the function name, which returns int and takes 4 parameters as shown in declaration.

Many APIs use structures to pass and retrieve values, as it is less expensive. It also uses constant data type for passing constant data and simple data types for passing built-in data types as seen in the previous declaration of the 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 the button you will see a MessageBox, which you called using API the function!!!

Using Structures

Working with APIs, which use complex structures, or structures inside structures, is somewhat more complex than using simple APIs. But once you understand the implementation then the whole API world is yours.

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

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

using System.Runtime.InteropServices;

Declare the structure, which is the 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 the API function:

[DllImport("kernel32")]
static extern void GetSystemInfo(ref SYSTEM_INFO pSI); 

Where ref is next to the method parameter keyword it causes a method to refer to the same variable that was passed into the method.

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

protected void button1_Click (object sender, System.EventArgs e)
{
	try
	{
		SYSTEM_INFO pSI = new SYSTEM_INFO();
		GetSystemInfo(ref pSI);
		//
		//
		//

Once you retrieve the structure, perform operations on the required parameter

e.g.listBox1.InsertItem (0,pSI.dwActiveProcessorMask.ToString());:

		//
		//
		//
	}
	catch(Exception er)
	{
		MessageBox.Show (er.Message);
	}
}

In the attached code I used two API's to retrieve various information from the system.

Note

I used beta version 1.0 for creating sample application. In Beta 2, declaration of API functions may be slightly different than 1.0.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Ajit Mungale
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberBibekananda Jena25-Jul-13 13:50 
QuestionC# API PinmemberJames Whyte9-Oct-12 23:03 
GeneralMy vote of 5 PinmemberSunnykumar0830-Oct-11 21:35 
GeneralMy vote of 4 Pinmembergreendragons20-Oct-10 10:05 
GeneralThank you very much! PinmemberMohammad Elsheimy24-May-10 10:59 
Generalchanging caption of a running application - plz help Pinmemberangelsherin22-Jun-08 0:35 
Generalchanging caption of a running application - plz help Pinmemberangelsherin22-Jun-08 0:34 
Generalchanging caption of a running application - plz help Pinmemberangelsherin22-Jun-08 0:34 
Hi,
 
In my project, i have to access the controls of a running application for ex, a Accessing all controls of a running windows
 
application developed in .net.I have to get all those controls of the running application and change its caption.
 
ex(buttonName,LabelName etc).I tried to implemented that ,but only caption of label alone gets changed and Button captions
 
and other control captions are not changed.I am working in C# windows applications.Please provide me the code in C#.Thanks in
 
advance.
 
regards,
Sherin
Generalproblem with Microsoft.Win32.Interop Pinmemberlang11-Jun-08 8:35 
GeneralWin32 and C# PinmemberWill230-Aug-07 5:34 
Generalshutdown computer Pinmembercanhthu31-Mar-07 4:47 
GeneralRe: shutdown computer PinmemberVirtual1ty17-Sep-07 7:30 
QuestionExitWindowEX function in Win32 API PinmemberMr. Ankur28-Mar-07 17:22 
AnswerRe: ExitWindowEX function in Win32 API PinmemberSauid Alam25-May-07 5:09 
GeneralAPI Call with lpString type Parameter PinmembertankSanju14-Dec-06 20:49 
Generalhi, please give the useful list of API' for writting a serialport application. Pinmemberpremkamalg27-Aug-06 21:03 
QuestionRe: hi, please give the useful list of API' for writting a serialport application. Pinmemberdogmatic6931-Oct-07 0:03 
GeneralCalling a function in Dll Pinmembercuongbao19712-Apr-06 8:16 
GeneralRe: Calling a function in Dll Pinmemberleducson7-Jul-06 8:44 
GeneralAPI Viewer in C# Code PinmemberRedaemon29-Dec-05 7:14 
GeneralDataSource selector window Pinmemberoquesada6-Oct-05 8:01 
QuestionHow to use Api to get information about HD Pinmemberkaszub25-May-05 22:20 
QuestionHow to call ODBC API SQLSetConnectAttr in C# Pinmemberedmondkc2-Jun-04 21:52 
Generalusing API example Pinmemberhas1sir28-Apr-04 21:39 
GeneralThe referenc component could not be found Pinmembertzuching24-Mar-04 14:01 
GeneralRe: The referenc component could not be found PinmemberIngo Fischer25-Aug-04 4:41 
GeneralRe: The referenc component could not be found PinmembercynusX14-Oct-08 14:43 
GeneralCalling C# from MFC/C++ apps PinmemberAlex Evans15-Feb-04 19:20 
Generalstrucutres as out parameters PinsussAnonymous7-Oct-03 2:14 
QuestionHow To call new Dial up connection thru API Pinsusssailash8-Jun-03 21:12 
Generalshut down windows Pinsussmoullouad mohammed25-May-03 7:36 
GeneralRe: shut down windows Pinmembermudassir ahmed31-Aug-05 1:21 
QuestionHow to disable Alt+ctrl+del in C# Pinmemberrm_babar6-May-03 8:10 
AnswerRe: How to disable Alt+ctrl+del in C# Pinmembershabonaa6-Jan-06 10:15 
GeneralCalling the FlashWindow API Function in C# PinmemberSidath8-Apr-03 15:49 
GeneralRe: Calling the FlashWindow API Function in C# Pinmemberpawnsdeleone15-Jan-04 5:13 
GeneralRe: Calling the FlashWindow API Function in C# Pinmembereyej18-May-06 10:37 
GeneralRe: Calling the FlashWindow API Function in C# Pinmembereyej18-May-06 10:45 
GeneralRe: Calling the FlashWindow API Function in C# Pinmembercust887021-Aug-07 3:20 
QuestionHow to convert array para? PinsussAnonymous4-Nov-02 19:45 
QuestionAnybody knows how to use MultiByteToWideChar in C#? Pinmemberjohnjy8-Sep-02 6:33 
AnswerRe: Anybody knows how to use MultiByteToWideChar in C#? Pinmembercchrism3-Nov-02 7:18 
GeneralRe: Anybody knows how to use MultiByteToWideChar in C#? Pinmembershamim1925-Mar-05 23:41 
GeneralRe: Anybody knows how to use MultiByteToWideChar in C#? Pinmembercchrism27-Mar-05 18:48 
Generalimport DLL build with VC6 PinsussAnonymous9-Jul-02 19:13 
GeneralRe: import DLL build with VC6 Pinmemberalinazari30-Oct-02 8:38 
GeneralRe: import DLL build with VC6 Pinmembercchrism3-Nov-02 7:13 
GeneralRe: import DLL build with VC6 Pinmemberleducson7-Jul-06 8:33 
GeneralCallbacks PinmemberMarco Cunha28-Dec-01 13:19 
GeneralRe: Callbacks Pinmembercchrism3-Nov-02 7:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141022.2 | Last Updated 11 Oct 2001
Article Copyright 2001 by Ajit Mungale
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid