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

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

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

  using System.Runtime.InteropServices;

  接着添加下面的代码来声明一个API: Selenium WebDriver

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

     }

  }

 //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# 中操作API的更多相关文章

  1. 在使用postman中操作api接口测试403解决方法

    在向Jenkins发送请求时收到了这样的403错误信息: No valid crumb was included in the request 后来通过google找到了解决方案. http://st ...

  2. C#中调用API

    介绍 API( Application Programming Interface ),我想大家不会陌生,它是我们Windows编程的常客,虽然基于.Net平台的C#有了强大的类库,但是,我们还是不能 ...

  3. 关于Django中的数据库操作API之distinct去重的一个误传

    转载自http://www.360doc.com/content/18/0731/18/58287567_774731201.shtml django提供的数据库操作API中的distinct()函数 ...

  4. HDFS中JAVA API的使用

    HDFS中JAVA API的使用   HDFS是一个分布式文件系统,既然是文件系统,就可以对其文件进行操作,比如说新建文件.删除文件.读取文件内容等操作.下面记录一下使用JAVA API对HDFS中的 ...

  5. VB中的API详解

    一.API是什么? 这个我本来不想说的,不过也许你知道其它人不知道,这里为了照顾一下新手,不得不说些废话,请大家谅解. Win32 API即为Microsoft 32位平台的应用程序编程接口(Appl ...

  6. elasticsearch中的API

    elasticsearch中的API es中的API按照大类分为下面几种: 文档API: 提供对文档的增删改查操作 搜索API: 提供对文档进行某个字段的查询 索引API: 提供对索引进行操作 查看A ...

  7. paip.复制文件 文件操作 api的设计uapi java python php 最佳实践

    paip.复制文件 文件操作 api的设计uapi java python php 最佳实践 =====uapi   copy() =====java的无,要自己写... ====php   copy ...

  8. Linux 编程中的API函数和系统调用的关系【转】

    转自:http://blog.chinaunix.net/uid-25968088-id-3426027.html 原文地址:Linux 编程中的API函数和系统调用的关系 作者:up哥小号 API: ...

  9. c#中操作word文档-四、对象模型

    转自:http://blog.csdn.net/ruby97/article/details/7406806 Word对象模型  (.Net Perspective) 本文主要针对在Visual St ...

随机推荐

  1. docker镜像文件导入与导出

    工作中经常需要拉取一些国外的镜像,但是网络限制等原因在公司拉取很慢,所以我习惯用亚马逊服务器拉取镜像,导出后下载到本地再导入开发环境 1. 查看镜像id sudo docker images REPO ...

  2. java web 学习总结之 Servlet/JSP 编码问题

    Servlet和JSP编码问题 字节流: 1.得到OutputStream  字节流 OutputStream os = response.getOutputStream();   用默认编码输出数据 ...

  3. [解读REST] 5.Web的需求 & 推导REST

    衔接上文[解读REST] 4.基于网络应用的架构风格,上文总结了一些适用于基于网络应用的架构风格,以及其评估结果.在前文的基础上,本文介绍一下Web架构的需求,以及在对Web的关键协议进行设计和改进的 ...

  4. 谦先生的程序员日志之我的hadoop大数据生涯一

    从一个初级程序员到高级程序员的经历 你好!我是谦先生,我是茫茫程序猿中的一猿,平凡又执着. 刚入行的时候说实话,啥都不懂,就懂点皮毛的java,各种被虐狗的感觉.又写js又写css又写后台...慢慢被 ...

  5. JDBC基本开发

    JDBC基本开发步骤 一:注册驱动 方式一:DriverManager.registerDriver(new Driver()); //存在注册两次问题,性能较低,消耗资源 方式二:Class.for ...

  6. ip完整验证详情

    不想跳坑就看一下 之前一直不太会写正则表达式,很多要用到正则表达式的都直接百度,像上次要用正则表达式验证是否是合法的ip地址,然后就上网找,结果就是没找到一个对的,今天就为大家贡献一下,写个对的,并做 ...

  7. LeetCode 405. Convert a Number to Hexadecimal (把一个数转化为16进制)

    Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s compl ...

  8. 【初学者必读】能让你月薪过万的5大web前端核心技能

    前言Web前端开发所涉及的内容主要包括W3C标准中的结构.行为和表现,那么这三项中我们需要掌握的核心技能是什么呢?看小编来为你揭开谜底的. 1.开发语言 HTML发展历史有二十多年,历经多次版本更新, ...

  9. 版本控制之四:SVN客户端重新设置帐号和密码(转)

    在第一次使用TortoiseSVN从服务器CheckOut的时候,会要求输入用户名和密码,这时输入框下面有个选项是保存认证信息,如果选了这个选项,那么以后就不用每次都输入一遍用户名密码了. 不过,如果 ...

  10. Lua 和 C 交互中虚拟栈的操作

    Lua 和 C 交互中虚拟栈的操作 /* int lua_pcall(lua_State *L, int nargs, int nresults, int msgh) * 以保护模式调用具有" ...