c#調用Win32 Api函數

來源:互聯網
上載者:User

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

有複雜參數和回呼函數的調用方式下次再談.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.