C# 和 Win32API

晨曦之光 发布于 2012/03/09 14:57
阅读 334
收藏 0
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#.

API(应用编程接口)是程序与处理器接口的命令集。最常用的就是在外部调用微软WINDOWS内部的进程。WINDOWS API包括成千的你可以使用的函数、结构、常量。这些函数是用C语言写的,在使用他们之前,你必须声明。 定义Dll的进程将相当的复杂,甚至比VB还复杂。你可以使用API Viewer工具得到API函数的声明,但是必须注意的是,它的参数类型跟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,微软函数类库(MFC)封装了大部分的Win32 API。ODBC API对提高数据库的操作速度大有好处。使用API,可以请求更底层的系统服务。API从简单的对话框到复杂的加密运算都提供支持。开发者应该知道如何在他们程序中使用API

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


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,

每种操作系统都有一套公用API和专有API。比如:Windows NT 支持MS-DOS, Win16, Win32, POSIX (便携式操作系统接口),OS/2 console API ;同时Windows 95 supports MS-DOS, Win16 和Win32 API。

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.

WIN16 是基于16位的处理器,并使用16位的值,它是一个独立的平台。比如:你可以运行TSR 程序在MS-DOS环境下。

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 是基于32位的处理器,并使用32位的值。他可用于任何操作系统,它的使用范围更广。

Win32 API has 32 prefix after the library name e.g. KERNEL32, USER32 etc?

Win32 API的DLL一般都具有32的后缀,比如:KERNEL32, USER32等。

All APIs are implemented using 3 Libraries.



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

比如:GlobalMemoryStatus 函数获得目前系统物理虚拟内存的使用信息。

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

在WIN32下,它的库名是 USER32.DLL

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.

比如:DrawIcon 画一个图标在指定的设备上。

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

比如:CreateBitmap 函数创建一个指定宽度、高度和颜色格式的位图。

C# and API:
Implementing API 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 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.

使用复杂的api之前,我们先用一个简单的MessageBox API作为列子。打开一个C#工程,增加一个按钮,在按钮的点击事件中,我们将显示一个信息框。


using System.Runtime.InteropServices;

public static extern int MessageBox(int h, string m, string c, int type);

Where DllImport 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.

DllImport属性用来指定包含外部方法的动态连接库的位置。 "User32.dll"指出了库名,static 指明它不属于特定的对象。extern 指明是一个外部的方法。带有DllImport 属性的方法必须带有修饰符extern 。

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

MessageBox 是一个汉数名,带四个参数返回一个int型值。

Many API 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.

许多API使用结构来传递、返回参数,这样可以减少复杂度。它也允许使用象MessageBox 函数那样,使用固定的参数。


protected void button1_Click (object sender, System.EventArgs e)

MessageBox (0,"API Message Box","API Demo",0);



Using structure 使用结构
Working with API, 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.

下面的列子,我们用GetSystemInfo API得到当前系统的信息。


using System.Runtime.InteropServices;

声明 GetSystemInfo 的参数结构:


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;




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)


GetSystemInfo(ref pSI);

Once you retrieve the structure perform operations on required parameter





catch(Exception er)

MessageBox.Show (er.Message);