如何在C#中使用DllImport和接口?

Dul*_*ttu 3 c# interface dllimport

我在代码中有几个DllImports,user32.dll我认为它们是在一个接口中声明的.但是,这给了我的错误说法public,static,extern不是每个项目有效.

示例接口代码如下:

public interface IWindowsFunctions
{
   [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
   static extern int MessageBox(int hWnd, string msg, string title, uint flags);
}
Run Code Online (Sandbox Code Playgroud)

是否有任何特定的方式在界面中使用它,或者是否有替代或接口不可能?

谢谢

Jus*_*tin 10

现在已经多次提到DLLImport是一个实现,因此无法在接口上定义,但我认为仍然值得一提的是,通常我将DLLImports分组为组织的"NativeMethods"类,如此:

internal static class NativeMethods
{
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int MessageBox(int hWnd, string msg, string title, uint flags);
}
Run Code Online (Sandbox Code Playgroud)

使用示例:

NativeMethods.MessageBox(myWnd, "Hello World", "Hello", flags);
Run Code Online (Sandbox Code Playgroud)