在C#程序设计中使用Win32类库

在C#程序设计中使用Win32类库
 
转自: CSDNBLOG
 
C# 用户经常提出两个问题:“我为什么要另外编写代码来使用内置于 Windows 中的功能?在框架中为什么没有相应的内容可以为我完成这一任务?”当框架小组构建他们的 .NET 部分时,他们评估了为使 .NET 程序员可以使用 Win32 而需要完成的工作,结果发现 Win32 API 集非常庞大。他们没有足够的资源为所有 Win32 API 编写托管接口、加以测试并编写文档,因此只能优先处理最重要的部分。许多常用操作都有托管接口,但是还有许多完整的 Win32 部分没有托管接口。

平台调用 (P/Invoke) 是完成这一任务的最常用方法。要使用 P/Invoke,您可以编写一个描述如何调用函数的原型,然后运行时将使用此信息进行调用。另一种方法是使用 Managed Extensions to C++ 来包装函数,这部分内容将在以后的专栏中介绍。

要理解如何完成这一任务,最好的办法是通过示例。在某些示例中,我只给出了部分代码;完整的代码可以通过下载获得。

简单示例

在第一个示例中,我们将调用 Beep() API 来发出声音。首先,我需要为 Beep() 编写适当的定义。查看 MSDN 中的定义,我发现它具有以下原型:

BOOL Beep(
  DWORD dwFreq,   // 声音频率
  DWORD dwDuration  // 声音持续时间
);

要用 C# 来编写这一原型,需要将 Win32 类型转换成相应的 C# 类型。由于 DWORD 是 4 字节的整数,因此我们可以使用 int 或 uint 作为 C# 对应类型。由于 int 是 CLS 兼容类型(可以用于所有 .NET 语言),以此比 uint 更常用,并且在多数情况下,它们之间的区别并不重要。bool 类型与 BOOL 对应。现在我们可以用 C# 编写以下原型:

public static extern bool Beep(int frequency, int duration);

这是相当标准的定义,只不过我们使用了 extern 来指明该函数的实际代码在别处。此原型将告诉运行时如何调用函数;现在我们需要告诉它在何处找到该函数。

我们需要回顾一下 MSDN 中的代码。在参考信息中,我们发现 Beep() 是在 kernel32.lib 中定义的。这意味着运行时代码包含在 kernel32.dll 中。我们在原型中添加 DllImport 属性将这一信息告诉运行时:

[DllImport("kernel32.dll")]

这就是我们要做的全部工作。下面是一个完整的示例,它生成的随机声音在二十世纪六十年代的科幻电影中很常见。

using System;
using System.Runtime.InteropServices;

namespace Beep
{
class Class1
  {
    [DllImport("kernel32.dll")]
    public static extern bool Beep(int frequency, int duration);

    static void Main(string[] args)
    {
      Random random = new Random();

      for (int i = 0; i < 10000; i++)
      {
       Beep(random.Next(10000), 100);
}
    }
  }
}
 

它的声响足以刺激任何听者!由于 DllImport 允许您调用 Win32 中的任何代码,因此就有可能调用恶意代码。所以您必须是完全受信任的用户,运行时才能进行 P/Invoke 调用。

枚举和常量

Beep() 可用于发出任意声音,但有时我们希望发出特定类型的声音,因此我们改用 MessageBeep()。MSDN 给出了以下原型:

BOOL MessageBeep(
  UINT uType // 声音类型
);

这看起来很简单,但是从注释中可以发现两个有趣的事实。

首先,uType 参数实际上接受一组预先定义的常量。

其次,可能的参数值包括 -1,这意味着尽管它被定义为 uint 类型,但 int 会更加适合。

对于 uType 参数,使用 enum 类型是合乎情理的。MSDN 列出了已命名的常量,但没有就具体值给出任何提示。由于这一点,我们需要查看实际的 API。

如果您安装了 Visual Studio? 和 C++,则 Platform SDK 位于 /Program Files/Microsoft Visual Studio .NET/Vc7/PlatformSDK/Include 下。

为查找这些常量,我在该目录中执行了一个 findstr。

findstr "MB_ICONHAND" *.h

它确定了常量位于 winuser.h 中,然后我使用这些常量来创建我的 enum 和原型:

public enum BeepType
{
  SimpleBeep = -1,
  IconAsterisk = 0x00000040,
  IconExclamation = 0x00000030,
  IconHand = 0x00000010,
  IconQuestion = 0x00000020,
  Ok = 0x00000000,
}

[DllImport("user32.dll")]
public static extern bool MessageBeep(BeepType beepType);
 

现在我可以用下面的语句来调用它: MessageBeep(BeepType.IconQuestion);
处理结构

有时我需要确定我笔记本的电池状况。Win32 为此提供了电源管理函数。

搜索 MSDN 可以找到 GetSystemPowerStatus() 函数。

BOOL GetSystemPowerStatus(
  LPSYSTEM_POWER_STATUS lpSystemPowerStatus
); 

此函数包含指向某个结构的指针,我们尚未对此进行过处理。要处理结构,我们需要用 C# 定义结构。我们从非托管的定义开始:

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;
}

这样,就可以方便地编写出 C# 原型:

[DllImport("kernel32.dll")]
public static extern bool GetSystemPowerStatus(
  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 的基本类型。
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用C++代码封装的win32操作类, 与MFC相似,对于学习SDK与C++是巨好的参考 Tutorials Menu of tutorials Tutorial 1: The Simplest Window Tutorial 2: Using Classes and Inheritance Tutorial 3: Using Messages to Create a Scribble Window Tutorial 4: Repainting the Window Tutorial 5: Wrapping a Frame around our Scribble Window Tutorial 6: Customising Window Creation Tutorial 7: Customising the Toolbar Tutorial 8: Loading and Saving Files Tutorial 9: Printing Tutorial 10: Finishing Touches Tutorial 1: The Simplest Window The following code uses Win32++ to create a window. This is all the code you need (in combination with Win32++) to create and display a simple window. Note that in order to add the Win32++ code to our program, we use an #include statement as shown below. #include "../Win32++/Wincore.h" INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPTSTR, int) { //Start Win32++ CWinApp MyApp; //Create a CWnd object CWnd MyWindow; //Create (and display) the window MyWindow.Create(); //Run the application return MyApp.Run(); } This program has four key steps: Start Win32++. We do this here by creating a CWinApp object called MyApp. Create a CWnd object called MyWindow. Create a default window by calling the Create function. Start the message loop, by calling the Run function. If you compile and run this program, you'll find that the application doesn't end when the window is closed. This is behaviour is normal. An illustration of how to use messages to control the windows behaviour (including closing the application) will be left until tutorial 3.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值