这个问题在这里已有答案:
我是Win32 API的新手 . 我正在尝试使用win32 API . 当我加载图像时,我得到一个句柄,但我也得到GetLastError响应0x06,句柄无效 . 我究竟做错了什么?
class Program
{
[DllImport("user32.dll", EntryPoint="LoadImage", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
static extern IntPtr LoadImage(IntPtr hinst, string lpszName, uint uType,
int cxDesired, int cyDesired, uint fuLoad);
[DllImport("kernel32.dll", EntryPoint ="GetLastError", CallingConvention = CallingConvention.StdCall)]
public static extern uint GetLastError();
static void Main(string[] args)
{
string path = @"c:\temp\bitmap.bmp";
IntPtr pointer = LoadImage(IntPtr.Zero, path, 0, 256, 256, 0x00008010);
uint result = GetLastError();
Console.WriteLine(pointer);
Console.WriteLine(result);
Console.ReadLine();
}
}
输出读数为:
-1576718263
6
我不确定我做错了什么 . 我想配置调用从文件加载图像,并且还有共享句柄,因为我将通过应用程序使用该句柄 .
谢谢,Maciej
1 回答
如果函数失败,您应该只调用
GetLastError
,如返回值所示 . 来自MSDN documentation:功能成功时调用它是没有意义的 .
你最好用以下的东西:
请记住,正如有些人在评论中指出的那样,您不应该从托管代码中调用
GetLastError
. 相反,您应该将SetLastError
设置为true
然后使用Marshal.GetLastWin32Error
. 有关详细信息,请参见here .