c#調用Win32 Api函數

在c#中可以通過互操作性服務using System.Runtime.InteropServices來調用window api函數.並且通過屬性來指定api函數的位置,以及調用方式,比如,我們要調用User32.dll裏的函數MessageBox(HWnd hwnd,LPCTSTR lpText,LPCTSTR lpCaption,UINT type)
首先引入名字空間
using System.Runtime.InteropServices;

其次定義一個靜態方法,並且指定調用的方式.其中用關鍵子[DllImport()]指定調用方式.
如:
 [DllImport("user32.dll", EntryPoint = "MessageBox", ExactSpelling = false)]
 public static extern int MessageBox(int hWnd, string text, string caption, uint type);

然後,該函數就可以象正常函數一樣的調用了.

完整代碼如下:

/*
 * write by zhanghua
 * date:2008/5/28
 *
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace NetMeeting.API
{
    public class Win32
    {
        [DllImport("user32.dll", EntryPoint = "MessageBox", ExactSpelling = false)]
        public static extern int MessageBox(int hWnd, string text, string caption, uint type);
    }
}

客戶調用幾乎和c#函數沒有什麼區別,如下:
using System;
using NetMeeting.API;
class test
{
    public static void Main(string[] agrs)
    {
            Win32.MessageBox(0,"hello ,this is a c# invoke win32 api","test",2);

    }
}

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