作为一名C#的初学者来说,使用API确是一件很头疼的问题。在使用API之间你必须知道如何在C#中使用结构、类型转换、安全/不安全代码,可控/不可控代码等许多知识。
一切从简单开始,复杂的大家一时不能接受。我们就从实现一个简单的MessageBox开始。首先打开VS.Net,创建一个新的C#工程,并添加一个Button按钮。当这个按钮被点击,则显示一个MessageBox对话框。
即然我们需要引用外来库,所以必须导入一个Namespace:
using System.Runtime.InteropServices; |
接着添加下面的代码来声明一个API:
[DllImport("User32.dll")] |
此处DllImport属性被用来从不可控代码中调用一方法。”User32.dll”则设定了类库名。DllImport属性指定dll的位置,这个dll中包括调用的外部方法。Static修饰符则声明一个静态元素,而这个元素属于类型本身而不是上面指定的对象。extern则表示这个方法将在工程外部执行,使用DllImport导入的方法必须使用extern修饰符。
MessageBox则是函数名,拥有4个参数,其返回值为数字。
大多数的API都能传递并返回值。
添中Click点击事件代码:
protected void button1_Click(object sender, System.EventArgs e) |
编译并运行这个程序,当你点击按钮后,你将会看到对话框,这便是你使用的API函数。
使用结构体
操作带有结构体的API比使用简单的API要复杂的多。但是一旦你掌握了API的过程,那个整个API世界将在你的掌握之中。
下面的例子中我们将使用GetSystemInfoAPI 来获取整个系统的信息。
第一步还是打开C#建立一个Form工程,同样的添中一个Button按钮,在代码窗中输入下面的代码,导入Namespace:
using System.Runtime.InteropServices; |
声明一个结构体,它将做为GetSystemInfo的一个参数:
|
声明API函数:
|
添加下面的代码至按钮的点击事件处理中:
首先创建一个SYSTEM_INFO结构体,并将其传递给GetSystemInfo函数。
|
一旦你接收到返回的结构体,那么就可以以返回的参数来执行操作了。
|
//CreatedBy Ajit Mungale
//程序补充 飞刀
namespaceUsingAPI
{
usingSystem;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.WinForms;
usingSystem.Data;
usingSystem.Runtime.InteropServices;
//Struct 收集系统信息
[StructLayout(LayoutKind.Sequential)]
publicstruct SYSTEM_INFO {
publicuint dwOemId;
publicuint dwPageSize;
publicuint lpMinimumApplicationAddress;
publicuint lpMaximumApplicationAddress;
public uintdwActiveProcessorMask;
publicuint dwNumberOfProcessors;
publicuint dwProcessorType;
publicuint dwAllocationGranularity;
publicuint dwProcessorLevel;
publicuint dwProcessorRevision;
}
//struct 收集内存情况
[StructLayout(LayoutKind.Sequential)]
publicstruct MEMORYSTATUS
{
publicuint dwLength;
publicuint dwMemoryLoad;
publicuint dwTotalPhys;
publicuint dwAvailPhys;
publicuint dwTotalPageFile;
publicuint dwAvailPageFile;
publicuint dwTotalVirtual;
publicuint dwAvailVirtual;
}
publicclass Form1 : System.WinForms.Form
{
privateSystem.ComponentModel.Container components;
privateSystem.WinForms.MenuItem menuAbout;
privateSystem.WinForms.MainMenu mainMenu1;
privateSystem.WinForms.ListBox listBox1;
privateSystem.WinForms.Button button1;
//获取系统信息
[DllImport("kernel32")]
staticextern void GetSystemInfo(ref SYSTEM_INFO pSI);
//获取内存信息
[DllImport("kernel32")]
staticextern void GlobalMemoryStatus(ref MEMORYSTATUS buf);
//处理器类型
publicconst int PROCESSOR_INTEL_386 = 386;
publicconst int PROCESSOR_INTEL_486 = 486;
publicconst int PROCESSOR_INTEL_PENTIUM = 586;
publicconst int PROCESSOR_MIPS_R4000 = 4000;
publicconst int PROCESSOR_ALPHA_21064 = 21064;
publicForm1()
{
InitializeComponent();
}
publicoverride void Dispose()
{
base.Dispose();
components.Dispose();
}
privatevoid 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);
}
protectedvoid menuAbout_Click (object sender, System.EventArgs e)
{
Formabt=new about() ;
abt.ShowDialog();
}
protectedvoid button1_Click (object sender, System.EventArgs e)
{
try
{
SYSTEM_INFOpSI = new SYSTEM_INFO();
GetSystemInfo(refpSI);
stringCPUType;
switch(pSI.dwProcessorType)
{
casePROCESSOR_INTEL_386 :
CPUType="Intel 386";
break;
casePROCESSOR_INTEL_486 :
CPUType ="Intel 486" ;
break;
casePROCESSOR_INTEL_PENTIUM :
CPUType ="Intel Pentium";
break;
casePROCESSOR_MIPS_R4000 :
CPUType ="MIPS R4000";
break;
casePROCESSOR_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获取返回值****************/
MEMORYSTATUSmemSt = new MEMORYSTATUS ();
GlobalMemoryStatus(ref memSt);
listBox1.InsertItem(10,"AvailablePage File :"+ (memSt.dwAvailPageFile/1024).ToString ());
listBox1.InsertItem(11,"AvailablePhysical Memory : " + (memSt.dwAvailPhys/1024).ToString());
listBox1.InsertItem(12,"AvailableVirtual Memory:" + (memSt.dwAvailVirtual/1024).ToString ());
listBox1.InsertItem(13,"Sizeof structur :" + memSt.dwLength.ToString());
listBox1.InsertItem(14,"MemoryIn Use :"+ memSt.dwMemoryLoad.ToString());
listBox1.InsertItem(15,"TotalPage Size :"+ (memSt.dwTotalPageFile/1024).ToString ());
listBox1.InsertItem(16,"TotalPhysical Memory :" + (memSt.dwTotalPhys/1024).ToString());
listBox1.InsertItem(17,"TotalVirtual Memory :" + (memSt.dwTotalVirtual/1024).ToString ());
}
catch(Exceptioner)
{
MessageBox.Show(er.Message);
}
}
publicstatic void Main(string[] args)
{
try
{
Application.Run(newForm1());
}
catch(Exceptioner)
{
MessageBox.Show(er.Message );
}
}
}
}
以上代码仅供参考,未经允许不得转载。