一 在C#程序设计中使用Win32类库
1、DWORD 是 4 字节的整数,因此我们可以使用 int 或 uint 作为 C# 对应类型。
2、bool 类型与 BOOL 对应。
示例一:调用 Beep() API 来发出声音
用 C# 编写以下原型:
[DllImport("kernel32.dll")]
public static extern bool Beep(int frequency, int duration);
示例二:枚举类型和常量
用C#编写一下原型:
public enum BeepType
{
SimpleBeep = -1,
IconAsterisk = 0x00000040,
IconExclamation = 0x00000030,
IconHand = 0x00000010,
IconQuestion = 0x00000020,
Ok = 0x00000000,
}
uType 参数实际上接受一组预先定义的常量,对于 uType 参数,使用 enum 类型是合乎情理的。
[DllImport("user32.dll")]
public static extern bool MessageBeep(BeepType beepType);
示例三:处理结构
typedef struct _SYSTEM_POWER_STATUS {
BYTE ACLineStatus;
BYTE BatteryFlag;
BYTE BatteryLifePercent;
BYTE Reserved1;
DWORD BatteryLifeTime;
DWORD BatteryFullLifeTime;
} SYSTEM_POWER_STATUS, *LPSYSTEM_POWER_STATUS;
然后,通过用 C# 类型代替 C 类型来得到 C# 版本。
struct SystemPowerStatus
{
byte ACLineStatus;
byte batteryFlag;
byte batteryLifePercent;
byte reserved1;
int batteryLifeTime;
int batteryFullLifeTime;
}
ref SystemPowerStatus systemPowerStatus);
在此原型中,我们用“ref”指明将传递结构指针而不是结构值。这是处理通过指针传递的结构的一般方法。
此函数运行良好,但是最好将 ACLineStatus 和 batteryFlag 字段定义为 enum:
enum ACLineStatus: byte
{
Offline = 0,
Online = 1,
Unknown = 255,
}
enum BatteryFlag: byte
{
High = 1,
Low = 2,
Critical = 4,
Charging = 8,
NoSystemBattery = 128,
Unknown = 255,
}
请注意,由于结构的字段是一些字节,因此我们使用 byte 作为该 enum 的基本类型
示例四:处理字符串
二 C# 中调用C++代码
[DllImport(“MyDLL.dll")]
//返回个int 类型
public static extern int mySum (int a1,int b1);
//DLL中申明
extern “C” __declspec(dllexport)
{
//a2 b2不能改变a1 b1
//a2=..
//b2=...
}
//参数传递int 类型
public static extern int mySum (ref int a1,ref int b1);
//DLL中申明
extern “C” __declspec(dllexport)
{
//可以改变 a1, b1
*a2=...
*b2=...
}
DLL 需传入char *类型
[DllImport(“MyDLL.dll")]
//传入值
public static extern int mySum (string
//DLL中申明
extern “C” __declspec(dllexport)
{
//改变astr2 bstr 2
}
DLL 需传出char *类型
[DllImport(“MyDLL.dll")]
// 传出值
public static extern int mySum (StringBuilder abuf, StringBuilder bbuf );
//DLL中申明
extern “C” __declspec(dllexport)
{
//传出char * 改变astr bstr -->abuf, bbuf可以被改变
}
DLL 回调函数
BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam)
using System;
using System.Runtime.InteropServices;
public delegate bool CallBack(int hwnd, int lParam); //定义委托函数类型
public class EnumReportApp
{
[DllImport("user32")]
public static extern int EnumWindows(CallBack x, int y);
public static void Main() {
CallBack myCallBack = new CallBack(EnumReportApp.Report); EnumWindows(myCallBack, 0);
}
public static bool Report(int hwnd, int lParam)
{
Console.Write("Window handle is ");
Console.WriteLine(hwnd); return true;
}
}
DLL
BOOL PtInRect(const RECT *lprc, POINT pt);
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct Point {
public int y;
[StructLayout(LayoutKind.Explicit)]
[FieldOffset(0)] public int left;
[FieldOffset(4)] public int top;
[FieldOffset(8)] public int right;
[FieldOffset(12)] public int bottom;
Class XXXX {
public static extern bool PtInRect(ref