如何为MAKEINTRESOURCE构建C#PInvoke?

如何为MAKEINTRESOURCE构建C#PInvoke?,c#,pinvoke,C#,Pinvoke,我正在尝试为LoadImage构建一个C#PInvoke,但我不知道如何传递name参数。我试图通过加载一个系统图标来测试它(在下面的示例中,用于WNDCLASSEX/RegisterClassEx,代替LoadIcon) 我试过三个签名: 建议仅将新的IntPtr置于该值附近即可: [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern Int

我正在尝试为LoadImage构建一个C#PInvoke,但我不知道如何传递name参数。我试图通过加载一个系统图标来测试它(在下面的示例中,用于WNDCLASSEX/RegisterClassEx,代替LoadIcon)

我试过三个签名:

建议仅将新的IntPtr置于该值附近即可:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr LoadImage(IntPtr hInst, IntPtr name, uint type, int cx, int cy, uint fuLoad);

User32.LoadImage(Kernal32.GetModuleHandle("user32.dll"), new IntPtr(32513), 1, 16, 16, 0);
根据,尝试将值作为字符串传递:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr LoadImage(IntPtr hInst, string name, uint type, int cx, int cy, uint fuLoad);

User32.LoadImage(Kernal32.GetModuleHandle("user32.dll"), "32513", 1, 16, 16, 0);
User32.LoadImage(Kernal32.GetModuleHandle("user32.dll"), "#32513", 1, 16, 16, 0);
建议简单地使用ushort就可以了

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr LoadImage(IntPtr hInst, ushort name, uint type, int cx, int cy, uint fuLoad);

User32.LoadImage(Kernal32.GetModuleHandle("user32.dll"), 32513, 1, 16, 16, 0);
在所有情况下,LoadImage函数都会失败(根据GetLastWin32Error),系统错误代码为:

错误\资源\类型\未找到1813(0x715):在映像文件中找不到指定的资源类型


这表明在user32.dll中找不到name的值。在C++中,您将使用MauntRealEnter获取名称值的指针。查看和,它表明我需要IntPtr用表示所需整数值的ushort替换其最终字节。如果这是最有可能出现的问题(并且简单地传递一个ushort不起作用),我该如何做呢?

它显示LoadIcon采用自己的自定义值(例如,32512表示默认应用程序图标),但user32.dll将其图标和光标与其他参考值(本例中为100)一起存储。所以问题是我传递的价值观,而不是我传递它们的方式

这个版本很好用:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr LoadImage(IntPtr hInst, ushort name, uint type, int cx, int cy, uint fuLoad);

LoadImage(Kernal32.GetModuleHandle(“User32.dll”),100,1,16,16,0

也许可以从中寻找灵感?第一个和第二个版本都可以(根据您是否需要资源id或名称,您可以同时使用这两个版本)。该错误只是表示此类型没有任何内容,打开user32.dll,您可以检查更新后的内容,指出我从pinvoke.net获得了字符串版本。@SimonMourier根据此处,值32513应该是有效的图标。如果它不在User32.dll中,它在哪里?这是LoadIcon,而不是LoadImage。如果使用头中的内置图标ID,则要将NULL作为第一个参数传递,而不是User32.dll模块。这在文档中,您可能更喜欢通过资源ID直接提取资源,因为有些资源是重定向的。@Zarat文档中说传递null仅用于使用独立资源或OEM映像。我找不到任何参考资料来解释OEM图像是什么。请查看LoadIcon和LoadCursor的文档。通过LoadImage加载图标是可行的,但是您不会在那里找到加载图标常量的文档,因为这不是您通常加载图标常量的方式。