推荐答案
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);本题详细解读
DllImport 特性的作用
DllImport 特性用于在 C# 中调用非托管代码,通常用于调用 Windows API 或其他非托管库中的函数。它允许你在 C# 代码中声明一个外部方法,并指定该方法的实现位于哪个 DLL 文件中。
DllImport 特性的用法
声明外部方法:使用
DllImport特性声明一个外部方法时,需要指定 DLL 文件的名称。例如,[DllImport("user32.dll")]表示该方法位于user32.dll中。指定字符集:可以通过
CharSet参数指定字符集。例如,CharSet.Auto表示根据操作系统自动选择字符集(Unicode 或 ANSI)。指定调用约定:可以通过
CallingConvention参数指定调用约定。默认情况下,CallingConvention为Winapi,这意味着它将使用平台的默认调用约定(通常是StdCall)。指定入口点:如果 DLL 中的函数名称与 C# 方法名称不同,可以使用
EntryPoint参数指定 DLL 中的函数名称。设置其他选项:
DllImport还有其他可选参数,如ExactSpelling、SetLastError等,用于进一步控制方法的调用行为。
示例代码
// www.javascriptcn.com code example
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
static void Main()
{
MessageBox(IntPtr.Zero, "Hello, World!", "Message", 0);
}
}在这个示例中,MessageBox 方法是从 user32.dll 中导入的,并在 Main 方法中调用,显示一个消息框。