飞刀 使用结构体 操作带有结构体的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); } } 全部程序代码见下一节。
|