The window API functions can be invoked in C # through the interoperability service using System.Runtime.InteropServices. And by attributes to specify the location of API functions, and how to invoke, for example, We're going to call the function in User32.dll MessageBox (HWnd hwnd,lpctstr lptext,lpctstr lpcaption,uint type)
First, we introduce the name space
Using System.Runtime.InteropServices;
Second, define a static method and specify how it is invoked. The calling method is specified with the key child [DllImport ()].
Such as:
[DllImport ("user32.dll", EntryPoint = "MessageBox", ExactSpelling = False)]
public static extern int MessageBox (int hWnd, string text, string caption, uint type);
The function can then be invoked like a normal function.
The complete code is as follows:
/*
* 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);
}
}
The client invocation is almost indistinguishable from the C # function, as follows:
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);
}
}
Calls with complex parameters and callback functions we'll talk about it next time.