介绍 

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

     }  

  }  

调用API全部代码 

  1   //Created By Ajit Mungale  
  2 
  3   //程序补充 飞刀  
  4 
  5   namespace UsingAPI  
  6 
  7   {  
  8 
  9   using System;  
 10 
 11   using System.Drawing;  
 12 
 13   using System.Collections;  
 14 
 15   using System.ComponentModel;  
 16 
 17   using System.WinForms;  
 18 
 19   using System.Data;  
 20 
 21   using System.Runtime.InteropServices;  
 22 
 23   //Struct 收集系统信息  
 24 
 25   [StructLayout(LayoutKind.Sequential)]  
 26 
 27   public struct SYSTEM_INFO {  
 28 
 29         public uint dwOemId;  
 30 
 31         public uint dwPageSize;  
 32 
 33         public uint lpMinimumApplicationAddress;  
 34 
 35         public uint lpMaximumApplicationAddress;  
 36 
 37         public uint dwActiveProcessorMask;  
 38 
 39         public uint dwNumberOfProcessors;  
 40 
 41         public uint dwProcessorType;  
 42 
 43         public uint dwAllocationGranularity;  
 44 
 45         public uint dwProcessorLevel;  
 46 
 47         public uint dwProcessorRevision;  
 48 
 49     }  
 50 
 51   //struct 收集内存情况  
 52 
 53   [StructLayout(LayoutKind.Sequential)]  
 54 
 55   public struct MEMORYSTATUS  
 56 
 57   {  
 58 
 59        public uint dwLength;  
 60 
 61        public uint dwMemoryLoad;  
 62 
 63        public uint dwTotalPhys;  
 64 
 65        public uint dwAvailPhys;  
 66 
 67        public uint dwTotalPageFile;  
 68 
 69        public uint dwAvailPageFile;  
 70 
 71        public uint dwTotalVirtual;  
 72 
 73        public uint dwAvailVirtual;  
 74 
 75   }  
 76 
 77   public class Form1 : System.WinForms.Form  
 78 
 79   {  
 80 
 81     private System.ComponentModel.Container components;  
 82 
 83     private System.WinForms.MenuItem menuAbout;  
 84 
 85     private System.WinForms.MainMenu mainMenu1;  
 86 
 87     private System.WinForms.ListBox listBox1;  
 88 
 89     private System.WinForms.Button button1;  
 90 
 91   //获取系统信息  
 92 
 93     [DllImport("kernel32")]  
 94 
 95     static extern void GetSystemInfo(ref SYSTEM_INFO pSI);  
 96 
 97     //获取内存信息  
 98 
 99     [DllImport("kernel32")]  
100 
101     static extern void GlobalMemoryStatus(ref MEMORYSTATUS buf);  
102 
103     //处理器类型  
104 
105     public const int PROCESSOR_INTEL_386 = 386;  
106 
107     public const int PROCESSOR_INTEL_486 = 486;  
108 
109     public const int PROCESSOR_INTEL_PENTIUM = 586;  
110 
111     public const int PROCESSOR_MIPS_R4000 = 4000;  
112 
113     public const int PROCESSOR_ALPHA_21064 = 21064;  
114 
115     public Form1()  
116 
117     {  
118 
119       InitializeComponent();  
120 
121     }  
122 
123     public override void Dispose()  
124 
125     {  
126 
127       base.Dispose();  
128 
129       components.Dispose();  
130 
131     }  
132 
133     private void InitializeComponent()  
134 
135      {  
136 
137        this.components = new System.ComponentModel.Container ();  
138 
139        this.mainMenu1 = new System.WinForms.MainMenu ();  
140 
141        this.button1 = new System.WinForms.Button ();  
142 
143        this.listBox1 = new System.WinForms.ListBox ();  
144 
145        this.menuAbout = new System.WinForms.MenuItem ();  
146 
147        mainMenu1.MenuItems.All = new System.WinForms.MenuItem[1] {this.menuAbout};  
148 
149        button1.Location = new System.Drawing.Point (148168);  
150 
151        button1.Size = new System.Drawing.Size (11232);  
152 
153        button1.TabIndex = 0;  
154 
155        button1.Text = "&Get Info";  
156 
157        button1.Click += new System.EventHandler (this.button1_Click);  
158 
159        listBox1.Location = new System.Drawing.Point (208);  
160 
161        listBox1.Size = new System.Drawing.Size (368147);  
162 
163        listBox1.TabIndex = 1;  
164 
165        menuAbout.Text = "&About";  
166 
167        menuAbout.Index = 0;  
168 
169        menuAbout.Click += new System.EventHandler (this.menuAbout_Click);  
170 
171        this.Text = "System Information - Using API";  
172 
173        this.MaximizeBox = false;  
174 
175        this.AutoScaleBaseSize = new System.Drawing.Size (513);  
176 
177        this.MinimizeBox = false;  
178 
179        this.Menu = this.mainMenu1;  
180 
181        this.ClientSize = new System.Drawing.Size (408213);  
182 
183        this.Controls.Add (this.listBox1);  
184 
185        this.Controls.Add (this.button1);  
186 
187     }  
188 
189     protected void menuAbout_Click (object sender, System.EventArgs e)  
190 
191     {  
192 
193        Form abt=new about() ;  
194 
195        abt.ShowDialog();  
196 
197     }  
198 
199     protected void button1_Click (object sender, System.EventArgs e)  
200 
201     {  
202 
203        try  
204 
205        {  
206 
207           SYSTEM_INFO pSI = new SYSTEM_INFO();  
208 
209           GetSystemInfo(ref pSI);  
210 
211           string CPUType;  
212 
213           switch (pSI.dwProcessorType)  
214 
215           {  
216 
217             case PROCESSOR_INTEL_386 :  
218 
219                CPUType= "Intel 386";  
220 
221                break;  
222 
223             case PROCESSOR_INTEL_486 :  
224 
225                CPUType = "Intel 486" ;  
226 
227               break;  
228 
229             case PROCESSOR_INTEL_PENTIUM :  
230 
231               CPUType = "Intel Pentium";  
232 
233               break;  
234 
235             case PROCESSOR_MIPS_R4000 :  
236 
237               CPUType = "MIPS R4000";  
238 
239               break;  
240 
241             case PROCESSOR_ALPHA_21064 :  
242 
243               CPUType = "DEC Alpha 21064";  
244 
245               break;  
246 
247             default :  
248 
249               CPUType = "(unknown)";  
250 
251          }  
252 
253          listBox1.InsertItem (0,"Active Processor Mask :"+pSI.dwActiveProcessorMask.ToString());  
254 
255          listBox1.InsertItem (1,"Allocation Granularity :"+pSI.dwAllocationGranularity.ToString());  
256 
257          listBox1.InsertItem (2,"Number Of Processors :"+pSI.dwNumberOfProcessors.ToString());  
258 
259          listBox1.InsertItem (3,"OEM ID :"+pSI.dwOemId.ToString());  
260 
261          listBox1.InsertItem (4,"Page Size:"+pSI.dwPageSize.ToString());  
262 
263          listBox1.InsertItem (5,"Processor Level Value:"+pSI.dwProcessorLevel.ToString());  
264 
265          listBox1.InsertItem (6,"Processor Revision:"+ pSI.dwProcessorRevision.ToString());  
266 
267          listBox1.InsertItem (7,"CPU type:"+CPUType);  
268 
269          listBox1.InsertItem (8,"Maximum Application Address: "+pSI.lpMaximumApplicationAddress.ToString());  
270 
271          listBox1.InsertItem (9,"Minimum Application Address:" +pSI.lpMinimumApplicationAddress.ToString());  
272 
273          /************** 从 GlobalMemoryStatus 获取返回值****************/  
274 
275          MEMORYSTATUS memSt = new MEMORYSTATUS ();  
276          GlobalMemoryStatus (ref memSt); 
277 
278          listBox1.InsertItem(10,"Available Page File :"+ (memSt.dwAvailPageFile/1024).ToString ());  
279 
280          listBox1.InsertItem(11,"Available Physical Memory : " + (memSt.dwAvailPhys/1024).ToString());  
281 
282          listBox1.InsertItem(12,"Available Virtual Memory:" + (memSt.dwAvailVirtual/1024).ToString ());  
283 
284          listBox1.InsertItem(13,"Size of structur :" + memSt.dwLength.ToString());  
285 
286          listBox1.InsertItem(14,"Memory In Use :"+ memSt.dwMemoryLoad.ToString());  
287 
288          listBox1.InsertItem(15,"Total Page Size :"+ (memSt.dwTotalPageFile/1024).ToString ());  
289 
290          listBox1.InsertItem(16,"Total Physical Memory :" + (memSt.dwTotalPhys/1024).ToString());  
291 
292          listBox1.InsertItem(17,"Total Virtual Memory :" + (memSt.dwTotalVirtual/1024).ToString ());  
293 
294        }  
295 
296        catch(Exception er)  
297 
298        {  
299 
300          MessageBox.Show (er.Message);  
301 
302        }  
303 
304     }  
305 
306     public static void Main(string[] args)  
307 
308     {  
309 
310       try  
311 
312        {  
313 
314           Application.Run(new Form1());  
315 
316        }  
317 
318        catch(Exception er)  
319 
320        {  
321 
322           MessageBox.Show (er.Message );  
323 
324        }  
325 
326    }  
327 
328   }  
329 

}
posted on 2005-12-09 23:04  CIPCHK  阅读(461)  评论(0)    收藏  举报