VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • c# 调用win32 API 函数

制作者:剑锋冷月 单位:无忧统计网,www.51stat.net
 

  在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);
  }
}
有复杂参数和回调函数的调用方式下次再谈.



相关教程