C# 和 API

來源:互聯網
上載者:User

API (Application Programming Interface) is a set of commands, which interfaces the programs with the processors. The most commonly used set of external procedures are those that make up Microsoft Windows itself. The Windows API contains thousands of functions, structures, and constants that you can declare and use in your projects. Those functions are written in the C language, however, so they must be declared before you can use them. The declarations for DLL procedures can become fairly complex. Specifically to C# it is more complex than VB. You can use API viewer tool to get API function declaration but you have to keep in mind the type of parameter which is different in C#.

API(應用編程介面)是程式與處理器介面的命令集。最常用的就是在外部調用微軟WINDOWS內部的進程。WINDOWS API包括成千的你可以使用的函數、結構、常量。這些函數是用C語言寫的,在使用他們之前,你必須聲明。 定義Dll的進程將相當的複雜,甚至比VB還複雜。你可以使用API Viewer工具得到API函數的聲明,但是必須注意的是,它的參數類型跟C#的不一樣。

Most of the advanced languages support API programming. The Microsoft Foundation Class Library (MFC) framework encapsulates a large portion of the Win32 (API). ODBC API Functions are useful for performing fast operations on database. With API your application can request lower-level services to perform on computer's operating system. As API supports thousands of functionality from simple Message Box to Encryption or Remote computing, developers should know how to implement API in their program.

大部分的進階語言都支援API,微軟函數類庫(MFC)封裝了大部分的Win32 API。ODBC API對提高資料庫的操作速度大有好處。使用API,可以請求更底層的系統服務。API從簡單的對話方塊到複雜的加密運算都提供支援。開發人員應該知道如何在他們程式中使用API

API has many types depending on OS, processor and functionality.

API有許多類型,(針對不同的作業系統、處理器…………)

OS specific API:

作業系統特有API:

Each operating system has common set of API's and some special e.g. Windows NT supports MS-DOS, Win16, Win32, POSIX (Portable Operating System Interface), OS/2 console API and Windows 95 supports MS-DOS, Win16 and Win32 APIs,

每種作業系統都有一套公用API和專有API。比如:Windows NT 支援MS-DOS, Win16, Win32, POSIX (攜帶型作業系統介面),OS/2 console API ;同時Windows 95 supports MS-DOS, Win16 和Win32 API。

Win16 和 Win32 API:

Win16 is an API created for 16-bit processor and relies on 16 bit values. It has platform independent nature e.g. you can tie Win16 programs to MS-DOS feature like TSR programs.

WIN16 是基於16位的處理器,並使用16位的值,它是一個獨立的平台。比如:你可以運行TSR 程式在MS-DOS環境下。

Win32 is an API created for 32-bit processor and relies on 32 bit values. It is portable to any operating system, wide range of processors and platform independent nature.

WIN32 是基於32位的處理器,並使用32位的值。他可用於任何作業系統,它的使用範圍更廣。

Win32 API has 32 prefix after the library name e.g. KERNEL32, USER32 etc?

Win32 API的DLL一般都具有32的尾碼,比如:KERNEL32, USER32等。

All APIs are implemented using 3 Libraries.

所有的API都在下面3個DLL中實現的。

      • Kernel
      • User
      • GDI
     1. KERNEL

It is the library named KERNEL32.DLL, which supports capabilities that are associated with OS such as

它的庫名是:KERNEL32.DLL,它是作業系統管理的API集

    • Process loading.    載入進程
    • Context switching.
    • File I/O.    檔案操作
    • Memory management.   記憶體管理

e.g. The GlobalMemoryStatus function obtains information about the system's current usage of both physical and virtual memory

比如:GlobalMemoryStatus 函數獲得目前系統物理虛擬記憶體的使用資訊。

      2. USER

This is the library named "USER32.DLL" in Win32.

在WIN32下,它的庫名是 USER32.DLL

This allows managing the entire user interfaces such as

它管理全部的使用者介面,比如:

    • Windows  視窗
    • Menus   菜單
    • Dialog Boxes  對話方塊
    • Icons etc.,    表徵圖等

e.g. The DrawIcon function draws an icon or cursor into the specified device context.

比如:DrawIcon 畫一個表徵圖在指定的裝置上。

       3. GDI (Graphical Device Interface)

This is the library named "GDI32.dll" in Win32. It is Graphic output library. Using GDI Windows draws windows, menus and dialog boxes.

這個DLL是GDI32.dll,它負責映像的輸出,使用GDI繪出視窗,菜單,對話方塊

      • It can create Graphical Output.    輸出映像
      • It can also use for storing graphical images. 儲存映像

e.g. The CreateBitmap function creates a bitmap with the specified width, height, and color format (color planes and bits-per-pixel).

比如:CreateBitmap 函數建立一個指定寬度、高度和顏色格式的位元影像。

C# and API:

Implementing API in C# is tuff job for beginners. Before implementing API you should know how to implement structure in C#, type conversion, safe/unsafe code, managed/unmanaged code and lots more.

C#中API的工具對初學者是相當不錯的。在C#使用中使用API之前,你應該Crowdsourced Security Testing道C#中如何使用結構、類型轉換,安全與不安全的程式碼等。

Before implementing complex API we will start with simple MessageBox API. To implement code for MessageBox API open new C# project and add one button. When button gets clicked the code will display Message Box.

使用複雜的api之前,我們先用一個簡單的MessageBox API作為列子。開啟一個C#工程,增加一個按鈕,在按鈕的點擊事件中,我們將顯示一個資訊框。

增加使用外部庫的命名空間:

          using System.Runtime.InteropServices;

下面聲明API

[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);

Where DllImport attribute used for calling method from unmanaged code. "User32.dll" indicates library name. DllImport attribute specifies the dll location that contains the implementation of an extern method. The static modifier used to declare a static member, which belongs to the type itself rather than to a specific object, extern is used to indicate that the method is implemented externally. A method that is decorated with the DllImport attribute must have the extern modifier.

DllImport屬性用來指定包含外部方法的動態串連庫的位置。 "User32.dll"指出了庫名,static 指明它不屬於特定的對象。extern 指明是一個外部的方法。帶有DllImport 屬性的方法必須帶有修飾符extern 。

MessageBox is function name, which returns int and takes 4 parameters as shown in declaration.

MessageBox 是一個漢數名,帶四個參數返回一個int型值。

Many API uses structure to pass and retrieve values, as it is less expensive. It also uses constant data type for passing constant data and simple data type for passing Built-in data type as seen in previous declaration of MessageBox function.

許多API使用結構來傳遞、返回參數,這樣可以減少複雜度。它也允許使用象MessageBox 函數那樣,使用固定的參數。

      在按鈕的點擊事件中增加下面代碼:

protected void button1_Click (object sender, System.EventArgs e)
{

MessageBox (0,"API Message Box","API Demo",0);

}

編譯並運行程式,點擊按鈕以後,你就可以看到一個由API調用的資訊框。

Using structure  使用結構

Working with API

, which uses complex structure or structure in structure, is somewhat complex than using simple API. But once you understand the implementation then whole API world is yours.

API中經常使用複雜的結構。不過一旦你明白了他們,將是很簡單的。

In next example we will use GetSystemInfo API which returns information about the current system.

下面的列子,我們用GetSystemInfo API得到當前系統的資訊。

第一步:增加一個C#視窗,並在上面增加一個按鈕,在視窗字碼頁增加一個命名空間:

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

         Where ref is method parameter keyword causes a method to refer to the same variable that was passed into the method.           

ref是一個標誌參量傳遞形式的關鍵字,它使傳入傳出的變數指向同一個變數(傳址傳遞)

            Add following code in button click event in which first create struct object and then pass it to function.

在按鈕點擊事件中增加下面的代碼,

protected void button1_Click (object sender, System.EventArgs e)
{

try
{

SYSTEM_INFO pSI = new SYSTEM_INFO();
GetSystemInfo(ref pSI);
//
//
//

Once you retrieve the structure perform operations on required parameter

比如:

listBox1.Items.Insert(0,pSI.dwActiveProcessorMask.ToString());

//
//
//



}



catch(Exception er)
{


MessageBox.Show (er.Message);

}


}

 

說明:原文出自:http://www.c-sharpcorner.com/1/CSandAPIAM.asp

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.