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

    }
}

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