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世界將在你的掌握之中。

  下面的例子中我們將使用GetSystemInfoAPI 來獲取整個系統的信息。

  第一步還是打開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);

     }

  }

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

       }

   }

  }

}


以上代碼僅供參考,未經允許不得轉載。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章