C#中调用Windows API的要点

来源:互联网 发布:tb程序化交易平台源码 编辑:程序博客网 时间:2024/06/15 01:50
C#中调用Windows API的要点

分类: VC++ C# 调用 vc dll 及windows API .NET
2009-02-04 13:37 阅读(1574) 评论(2) 收藏 举报

介绍

  API(Application Programming Interface),我想大家不会陌生,它是我们Windows编程的常客,虽然基于.Net平台的C#有了强大的类库,但是,我们还是不能否认API在Windows编程中的重要性。大多数的编程语言都支持API编程,而.Net平台中的MFC(Microsoft Foundation Class Library)构架本身就封装了大部分的API。

  做为程序员,我们需要了解API从字面上了解便是编程接口,因此,做为开发者,需要了解的只是API的使用方法。

  API根据操作系统、处理器及功能性的不同而拥有很多不同的类型。   操作系统特用的API:

  每种操作系统都有许多通用的API以及一些特用的API,这些特用的API只能在当前操作系统中执行。

  例如:

  Windows NT 支持 MS-DOS, Win16, Win32, POSIX (Portable Operating System Interface), OS/2 console API; 而 Windows 95 支持 MS-DOS, Win16 以及 Win32 APIs.

  Win16 & Win32 API:

  Win16是为十六位处理器开发的,早期的操作系统均支持。

  Win32则是为32位处理器开发。它可移植性强,被大部分的处理器所支持。

  Win32 API在库名后有一个”32”后缀。比如KERNEL32,USER32等。

  所有API在下面3个库中得以运行:
  Kernel
  User
  GDI



  1. KERNEL

  他的库名为 KERNEL32.DLL, 他主要用于产生与操作系统之间的关联:

  程序加载
  上下文选择.
  文件输入输出.
  内存管理.
  例如: GlobalMemoryStatus 函数就包括当前物理内存及虚拟内存的使用信息。

  2. USER

  这个类库在Win32中名叫 USER32.DLL。

  它允许管理全部的用户接口,比如:

  窗口
  菜单
  对话框
  图标等.,
  例如: DrawIcon 函数将在指定的设备关联上“画”出图标或者鼠标。

  3. GDI (Graphical Device Interface)

  它在Win32中的库名为:GDI32.dll,它是图形输出库。使用GDI Windows“画”出窗口、菜单以及对话框等:

  它能创建图形输出.
  它也能保存图形文件.
  例如: CreateBitmap 函数就能通过指定的长、宽、颜色创建一个位图。





  C# 中操作API:

  作为初学者来说,在C#中使用API确是一件令人头疼的问题。在使用API之间你必须知道如何在C#中使用结构、类型转换、安全/不安全代码,可控/不可控代码等许多知识。

  一切从简单开始,复杂的大家一时不能接受。我们就从实现一个简单的MessageBox开始。首先打开VS.Net ,创建一个新的C#工程,并添加一个Button按钮。当这个按钮被点击,则显示一个MessageBox对话框。

  即然我们需要引用外来库,所以必须导入一个Namespace:

  using System.Runtime.InteropServices;




  接着添加下面的代码来声明一个API:
  [DllImport("User32.dll")]

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



  此处DllImport属性被用来从不可控代码中调用一方法。”User32.dll”则设定了类库名。DllImport属性指定dll的位置,这个dll中包括调用的外部方法。Static修饰符则声明一个静态元素,而这个元素属于类型本身而不是上面指定的对象。extern则表示这个方法将在工程外部执行,使用DllImport导入的方法必须使用extern修饰符。

  MessageBox 则是函数名,拥有4个参数,其返回值为数字。

  大多数的API都能传递并返回值。

  添中Click点击事件代码:
  protected void button1_Click(object sender, System.EventArgs e)

  {

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

  }





  编译并运行这个程序,当你点击按钮后,你将会看到对话框,这便是你使用的API函数。

  使用结构体

  操作带有结构体的API比使用简单的API要复杂的多。但是一旦你掌握了API的过程,那个整个API世界将在你的掌握之中。

  下面的例子中我们将使用GetSystemInfo API 来获取整个系统的信息。

  第一步还是打开C#建立一个Form工程,同样的添中一个Button按钮,在代码窗中输入下面的代码,导入Namespace:
  using System.Runtime.InteropServices;



  声明一个结构体,它将做为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;

  }




  声明API函数:


  [DllImport("kernel32")]

  static extern void GetSystemInfo(ref SYSTEM_INFO pSI);




  添加下面的代码至按钮的点击事件处理中:

  首先创建一个SYSTEM_INFO结构体,并将其传递给GetSystemInfo函数。


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

  {

      try

      {

          SYSTEM_INFO pSI = new SYSTEM_INFO();

          GetSystemInfo(ref pSI);

          //

          //

          //




  一旦你接收到返回的结构体,那么就可以以返回的参数来执行操作了。


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

          //

          //

          //

     }

     catch(Exception er)

     {

          MessageBox.Show (er.Message);

     }

  }









view plain
调用API全部代码

  //Created By Ajit Mungale

  //程序补充 飞刀

  namespace UsingAPI

  {

  using System;

  using System.Drawing;

  using System.Collections;

  using System.ComponentModel;

  using System.WinForms;

  using System.Data;

  using System.Runtime.InteropServices;

  //Struct 收集系统信息

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

    }

  //struct 收集内存情况

  [StructLayout(LayoutKind.Sequential)]

  public struct MEMORYSTATUS

  {

       public uint dwLength;

       public uint dwMemoryLoad;

       public uint dwTotalPhys;

       public uint dwAvailPhys;

       public uint dwTotalPageFile;

       public uint dwAvailPageFile;

       public uint dwTotalVirtual;

       public uint dwAvailVirtual;

  }

  public class Form1 : System.WinForms.Form

  {

    private System.ComponentModel.Container components;

    private System.WinForms.MenuItem menuAbout;

    private System.WinForms.MainMenu mainMenu1;

    private System.WinForms.ListBox listBox1;

    private System.WinForms.Button button1;

  //获取系统信息

    [DllImport("kernel32")]

    static extern void GetSystemInfo(ref SYSTEM_INFO pSI);

    //获取内存信息

    [DllImport("kernel32")]

    static extern void GlobalMemoryStatus(ref MEMORYSTATUS buf);

    //处理器类型

    public const int PROCESSOR_INTEL_386 = 386;

    public const int PROCESSOR_INTEL_486 = 486;

    public const int PROCESSOR_INTEL_PENTIUM = 586;

    public const int PROCESSOR_MIPS_R4000 = 4000;

    public const int PROCESSOR_ALPHA_21064 = 21064;

    public Form1()

    {

      InitializeComponent();

    }

    public override void Dispose()

    {

      base.Dispose();

      components.Dispose();

    }

    private void InitializeComponent()

     {

       this.components = new System.ComponentModel.Container ();

       this.mainMenu1 = new System.WinForms.MainMenu ();

       this.button1 = new System.WinForms.Button ();

       this.listBox1 = new System.WinForms.ListBox ();

       this.menuAbout = new System.WinForms.MenuItem ();

       mainMenu1.MenuItems.All = new System.WinForms.MenuItem[1] {this.menuAbout};

       button1.Location = new System.Drawing.Point (148, 168);

       button1.Size = new System.Drawing.Size (112, 32);

       button1.TabIndex = 0;

       button1.Text = "&Get Info";

       button1.Click += new System.EventHandler (this.button1_Click);

       listBox1.Location = new System.Drawing.Point (20, 8);

       listBox1.Size = new System.Drawing.Size (368, 147);

       listBox1.TabIndex = 1;

       menuAbout.Text = "&About";

       menuAbout.Index = 0;

       menuAbout.Click += new System.EventHandler (this.menuAbout_Click);

       this.Text = "System Information - Using API";

       this.MaximizeBox = false;

       this.AutoScaleBaseSize = new System.Drawing.Size (5, 13);

       this.MinimizeBox = false;

       this.Menu = this.mainMenu1;

       this.ClientSize = new System.Drawing.Size (408, 213);

       this.Controls.Add (this.listBox1);

       this.Controls.Add (this.button1);

    }

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

    {

       Form abt=new about() ;

       abt.ShowDialog();

    }

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

    {

       try

       {

          SYSTEM_INFO pSI = new SYSTEM_INFO();

          GetSystemInfo(ref pSI);

          string CPUType;

          switch (pSI.dwProcessorType)

          {

            case PROCESSOR_INTEL_386 :

               CPUType= "Intel 386";

               break;

            case PROCESSOR_INTEL_486 :

               CPUType = "Intel 486" ;

              break;

            case PROCESSOR_INTEL_PENTIUM :

              CPUType = "Intel Pentium";

              break;

            case PROCESSOR_MIPS_R4000 :

              CPUType = "MIPS R4000";

              break;

            case PROCESSOR_ALPHA_21064 :

              CPUType = "DEC Alpha 21064";

              break;

            default :

              CPUType = "(unknown)";

         }

         listBox1.InsertItem (0,"Active Processor Mask :"+pSI.dwActiveProcessorMask.ToString());

         listBox1.InsertItem (1,"Allocation Granularity :"+pSI.dwAllocationGranularity.ToString());

         listBox1.InsertItem (2,"Number Of Processors :"+pSI.dwNumberOfProcessors.ToString());

         listBox1.InsertItem (3,"OEM ID :"+pSI.dwOemId.ToString());

         listBox1.InsertItem (4,"Page Size:"+pSI.dwPageSize.ToString());

         listBox1.InsertItem (5,"Processor Level Value:"+pSI.dwProcessorLevel.ToString());

         listBox1.InsertItem (6,"Processor Revision:"+ pSI.dwProcessorRevision.ToString());

         listBox1.InsertItem (7,"CPU type:"+CPUType);

         listBox1.InsertItem (8,"Maximum Application Address: "+pSI.lpMaximumApplicationAddress.ToString());

         listBox1.InsertItem (9,"Minimum Application Address:" +pSI.lpMinimumApplicationAddress.ToString());

         /************** 从 GlobalMemoryStatus 获取返回值****************/

         MEMORYSTATUS memSt = new MEMORYSTATUS ();
         GlobalMemoryStatus (ref memSt);

         listBox1.InsertItem(10,"Available Page File :"+ (memSt.dwAvailPageFile/1024).ToString ());

         listBox1.InsertItem(11,"Available Physical Memory : " + (memSt.dwAvailPhys/1024).ToString());

         listBox1.InsertItem(12,"Available Virtual Memory:" + (memSt.dwAvailVirtual/1024).ToString ());

         listBox1.InsertItem(13,"Size of structur :" + memSt.dwLength.ToString());

         listBox1.InsertItem(14,"Memory In Use :"+ memSt.dwMemoryLoad.ToString());

         listBox1.InsertItem(15,"Total Page Size :"+ (memSt.dwTotalPageFile/1024).ToString ());

         listBox1.InsertItem(16,"Total Physical Memory :" + (memSt.dwTotalPhys/1024).ToString());

         listBox1.InsertItem(17,"Total Virtual Memory :" + (memSt.dwTotalVirtual/1024).ToString ());

       }

       catch(Exception er)

       {

         MessageBox.Show (er.Message);

       }

    }

    public static void Main(string[] args)

    {

      try

       {

          Application.Run(new Form1());

       }

       catch(Exception er)

       {

          MessageBox.Show (er.Message );

       }

   }

  }

}





C#中调用Windows API的要点
日期:2003年12月11日 作者:佚名 人气:586 查看:[大字体 中字体 小字体]

在.Net Framework SDK文档中,关于调用Windows API的指示比较零散,并且其中稍全面一点的是针对Visual Basic .net讲述的。本文将C#中调用API的要点汇集如下,希望给未在C#中使用过API的朋友一点帮助。另外如果安装了Visual Studio .net的话,在C:/Program Files/Microsoft Visual Studio .NET/FrameworkSDK/Samples/Technologies/Interop/PlatformInvoke/WinAPIs/CS目录下有大量的调用API的例子。
一、调用格式
using System.Runtime.InteropServices; //引用此名称空间,简化后面的代码
...
//使用DllImportAttribute特性来引入api函数,注意声明的是空方法,即方法体为空。
[DllImport("user32.dll")]
public static extern ReturnType FunctionName(type arg1,type arg2,...);
//调用时与调用其他方法并无区别

可以使用字段进一步说明特性,用逗号隔开,如:
[ DllImport( "kernel32", EntryPoint="GetVersionEx" )]
DllImportAttribute特性的公共字段如下:
1、CallingConvention 指示向非托管实现传递方法参数时所用的 CallingConvention 值。
CallingConvention.Cdecl : 调用方清理堆栈。它使您能够调用具有 varargs 的函数。
CallingConvention.StdCall : 被调用方清理堆栈。它是从托管代码调用非托管函数的默认约定。
2、CharSet 控制调用函数的名称版本及指示如何向方法封送 String 参数。
此字段被设置为 CharSet 值之一。如果 CharSet 字段设置为 Unicode,则所有字符串参数在传递到非托管实现之前都转换成 Unicode 字符。这还导致向 DLL EntryPoint 的名称中追加字母“W”。如果此字段设置为 Ansi,则字符串将转换成 ANSI 字符串,同时向 DLL EntryPoint 的名称中追加字母“A”。大多数 Win32 API 使用这种追加“W”或“A”的约定。如果 CharSet 设置为 Auto,则这种转换就是与平台有关的(在 Windows NT 上为 Unicode,在 Windows 98 上为 Ansi)。CharSet 的默认值为 Ansi。CharSet 字段也用于确定将从指定的 DLL 导入哪个版本的函数。CharSet.Ansi 和 CharSet.Unicode 的名称匹配规则大不相同。对于 Ansi 来说,如果将 EntryPoint 设置为“MyMethod”且它存在的话,则返回“MyMethod”。如果 DLL 中没有“MyMethod”,但存在“MyMethodA”,则返回“MyMethodA”。对于 Unicode 来说则正好相反。如果将 EntryPoint 设置为“MyMethod”且它存在的话,则返回“MyMethodW”。如果 DLL 中不存在“MyMethodW”,但存在“MyMethod”,则返回“MyMethod”。如果使用的是 Auto,则匹配规则与平台有关(在 Windows NT 上为 Unicode,在 Windows 98 上为 Ansi)。如果 ExactSpelling 设置为 true,则只有当 DLL 中存在“MyMethod”时才返回“MyMethod”。

3、EntryPoint 指示要调用的 DLL 入口点的名称或序号。
如果你的方法名不想与api函数同名的话,一定要指定此参数,例如:
[DllImport("user32.dll",CharSet="CharSet.Auto",EntryPoint="MessageBox")]
public static extern int MsgBox(IntPtr hWnd,string txt,string caption, int type);

4、ExactSpelling 指示是否应修改非托管 DLL 中的入口点的名称,以与 CharSet 字段中指定的 CharSet 值相对应。如果为 true,则当 DllImportAttribute.CharSet 字段设置为 CharSet 的 Ansi 值时,向方法名称中追加字母 A,当 DllImportAttribute.CharSet 字段设置为 CharSet 的 Unicode 值时,向方法的名称中追加字母 W。此字段的默认值是 false。
5、PreserveSig 指示托管方法签名不应转换成返回 HRESULT、并且可能有一个对应于返回值的附加 [out, retval] 参数的非托管签名。
6、SetLastError 指示被调用方在从属性化方法返回之前将调用 Win32 API SetLastError。 true 指示调用方将调用 SetLastError,默认为 false。运行时封送拆收器将调用 GetLastError 并缓存返回的值,以防其被其他 API 调用重写。用户可通过调用 GetLastWin32Error 来检索错误代码。

二、参数类型:
1、数值型直接用对应的就可。(DWORD -> int , WORD -> Int16)
2、API中字符串指针类型 -> .net中string
3、API中句柄 (dWord) -> .net中IntPtr
4、API中结构 -> .net中结构或者类。注意这种情况下,要先用StructLayout特性限定声明结构或类
公共语言运行库利用StructLayoutAttribute控制类或结构的数据字段在托管内存中的物理布局,即类或结构需要按某种方式排列。如果要将类传递给需要指定布局的非托管代码,则显式控制类布局是重要的。它的构造函数中用LayoutKind值初始化 StructLayoutAttribute 类的新实例。 LayoutKind.Sequential 用于强制将成员按其出现的顺序进行顺序布局。
LayoutKind.Explicit 用于控制每个数据成员的精确位置。利用 Explicit, 每个成员必须使用 FieldOffsetAttribute 指示此字段在类型中的位置。如:
[StructLayout(LayoutKind.Explicit, Size=16, CharSet=CharSet.Ansi)]
public class MySystemTime
{
[FieldOffset(0)]public ushort wYear;
[FieldOffset(2)]public ushort wMonth;
[FieldOffset(4)]public ushort wDayOfWeek;
[FieldOffset(6)]public ushort wDay;
[FieldOffset(8)]public ushort wHour;
[FieldOffset(10)]public ushort wMinute;
[FieldOffset(12)]public ushort wSecond;
[FieldOffset(14)]public ushort wMilliseconds;
}
下面是针对API中OSVERSIONINFO结构,在.net中定义对应类或结构的例子:
/**********************************************
* API中定义原结构声明
* OSVERSIONINFOA STRUCT
* dwOSVersionInfoSize DWORD ?
* dwMajorVersion DWORD ?
* dwMinorVersion DWORD ?
* dwBuildNumber DWORD ?
* dwPlatformId DWORD ?
* szCSDVersion BYTE 128 dup (?)
* OSVERSIONINFOA ENDS
*
* OSVERSIONINFO equ <OSVERSIONINFOA>
*********************************************/

//.net中声明为类
[ StructLayout( LayoutKind.Sequential )]
public class OSVersionInfo
{
public int OSVersionInfoSize;
public int majorVersion;
public int minorVersion;
public int buildNumber;
public int platformId;

[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=128 )]
public String versionString;
}
//或者
//.net中声明为结构
[ StructLayout( LayoutKind.Sequential )]
public struct OSVersionInfo2
{
public int OSVersionInfoSize;
public int majorVersion;
public int minorVersion;
public int buildNumber;
public int platformId;

[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=128 )]
public String versionString;
}

此例中用到MashalAs特性,它用于描述字段、方法或参数的封送处理格式。用它作为参数前缀并指定目标需要的数据类型。例如,以下代码将两个参数作为数据类型长指针封送给 Windows API 函数的字符串 (LPStr):
[MarshalAs(UnmanagedType.LPStr)]
String existingfile;
[MarshalAs(UnmanagedType.LPStr)]
String newfile;

注意结构作为参数时候,一般前面要加上ref修饰符,否则会出现错误:对象的引用没有指定对象的实例。
[ DllImport( "kernel32", EntryPoint="GetVersionEx" )]
public static extern bool GetVersionEx2( ref OSVersionInfo2 osvi );

三、如何保证使用托管对象的平台调用成功?
如果在调用平台 invoke 后的任何位置都未引用托管对象,则垃圾回收器可能将完成该托管对象。这将释放资源并使句柄无效,从而导致平台invoke 调用失败。用 HandleRef 包装句柄可保证在平台 invoke 调用完成前,不对托管对象进行垃圾回收。
例如下面:
FileStream fs = new FileStream( "a.txt", FileMode.Open );
StringBuilder buffer = new StringBuilder( 5 );
int read = 0;
ReadFile(fs.Handle, buffer, 5, out read, 0 ); //调用Win API中的ReadFile函数
由于fs是托管对象,所以有可能在平台调用还未完成时候被垃圾回收站回收。将文件流的句柄用HandleRef包装后,就能避免被垃圾站回收:
[ DllImport( "Kernel32.dll" )]
public static extern bool ReadFile(
HandleRef hndRef,
StringBuilder buffer,
int numberOfBytesToRead,
out int numberOfBytesRead,
ref Overlapped flag );
......
......
FileStream fs = new FileStream( "HandleRef.txt", FileMode.Open );
HandleRef hr = new HandleRef( fs, fs.Handle );
StringBuilder buffer = new StringBuilder( 5 );
int read = 0;
// platform invoke will hold reference to HandleRef until call ends
ReadFile( hr, buffer, 5, out read, 0 );
原创粉丝点击