2012-04-12 60 views

回答

1

这里是在行动DllImport属性的一个简单的例子:

using System.Runtime.InteropServices; 
class C 
{ 
    [DllImport("user32.dll")] 
    public static extern int MessageBoxA(int h, string m, string c, int type); 
    public static int Main() 
    { 
     return MessageBoxA(0, "Hello World!", "Caption", 0); 
    } 
} 

此示例显示声明在本机中实现的C#方法的最低要求e DLL。方法C.MessageBoxA()使用静态和外部修饰符声明,并具有DllImport属性,该属性告知编译器该实现来自user32.dll,使用默认名称MessageBoxA

参考this link

2

这是Microsoft example

class PlatformInvokeTest 
{ 
    [DllImport("msvcrt.dll")] 
    public static extern int puts(string c); 
    [DllImport("msvcrt.dll")] 
    internal static extern int _flushall(); 

    public static void Main() 
    { 
     puts("Test"); 
     _flushall(); 
    } 
} 

如果您需要从本地DLL生成C#的DllImport声明,看这个帖子:Generate C# DLLImport declarations from a native dll

2

取决于你想要什么......我在我的代码是这样的,但这使用Win32 API的DLL

[DllImport("user32.dll")] 
static extern IntPtr GetForegroundWindow(); 

然后就叫

GetForegroundWindow() 

好像在类里定义的一样