2012-04-12 66 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() 

好像在類裏定義的一樣