程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 如何使用C#操作WinAPI

如何使用C#操作WinAPI

編輯:C#入門知識

Windows API是對Windows操作系統的API函數,在C#中調用Windows API的實質是托管代碼對非托管代碼的調用。

主要使用的格式就是:

 

using System.Runtime.InteropServices;

namespace TestWinAPI1
{
class Program
{
static void Main(string[] args)
{
Beep(100, 100);
}


[DllImport("kernel32", CharSet = CharSet.Ansi)]
public static extern bool Beep(int frequery, int duration);
}
}

 

其中的Beep就是Win API的調用,使用[DllImport("kernel32")]屬性進行調用。

這個函數在MSDN中的原本定義是:

 

C++ 
BOOL WINAPI Beep(
__in DWORD dwFreq,
__in DWORD dwDuration
);

 

我們想要調用BeepAPI,就必須:

1.將DWORD對應為C#中的int,相應的參數個數和位置設置正確

2.調用的函數名和WinAPI中的函數名一致

這樣,我們在C#中就可以使用Win API對Windows進行操作。

 

這裡幾個資源是使用WindowsAPI不可或缺的:

MSDN:http://msdn.microsoft.com/en-us/library/ee663300(VS.85).aspx

推薦的入門教程:http://www.docin.com/p-4510006.html

 

 

使用WINAPI的難點:

 

1.C++中的各個數據類型如何對應到C#中?

使用C#中的那個數據類型對應那個C++的數據類型沒有唯一的規定,但是應該站在內存使用的角度,選擇內存占用大小一致。

當C++中存在指針的時候,我們可以使用ref來傳遞指針

 

2.如果C++中定義了數據結構如何操作?

我們也應該在C#中定義與之存儲結構一致的數據結構

 

以下是用WinAPI 模擬鼠標定位和單機左鍵的操作:

 

\\代碼
namespace TestWinAPI1
{
public struct Point
{
int x;
int y;
}
class Program
{
static void Main(string[] args)
{
Point point = new Point();
bool getResult = GetCursorPos(ref point);
int setRight = SetCursorPos(27, 881);
MouseClick("left");
}

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetCursorPos(ref Point point);

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetCursor();


[DllImport("user32")]
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved