在c#中使用win32从窗口获取位图:我在哪里出错了
本文关键字:位图 在哪里 错了 出错 获取 窗口 win32 | 更新日期: 2023-09-27 18:01:26
我需要检索与程序相关的所有窗口的屏幕截图。现在我只是想让这个工作的主窗口。
在image = Image.FromHbitmap(mem);
之后,我得到的错误是"GDI+中发生的一般错误"。我试图遵循这个教程
我想我把指针弄乱了,特别是在这三行:
IntPtr oldBmp = (IntPtr)Win32Stuff.SelectObject(mem, windowImage);
Win32Stuff.BitBlt(mem, 0, 0, windowwidth, windowheight, windowDC, 0, 0, 13369376);
Win32Stuff.SelectObject(mem, oldBmp);
如果我理解正确,oldBmp和mem指向windowImage,然后mem指向BitBlt的输出,那么我没有得到现在mem指向oldBmp的这行。我试着把它注释出来,看看这是不是搞砸了,但我得到了相同的通用错误。
以下是完整的代码:
public static class Win32Stuff
{
[DllImport("user32.dll", EntryPoint = "ReleaseDC")]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc);
[DllImport("user32.dll", EntryPoint = "GetWindowDC")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("gdi32", EntryPoint = "CreateCompatibleDC")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32", EntryPoint = "CreateCompatibleBitmap")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
[DllImport("gdi32", EntryPoint = "SelectObject")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32", EntryPoint = "BitBlt")]
public static extern bool BitBlt(IntPtr hDestDC, int X, int Y, int nWidth, int nHeight, IntPtr hSrcDC, int SrcX, int SrcY, int Rop);
[DllImport("gdi32", EntryPoint = "DeleteDC")]
public static extern IntPtr DeleteDC(IntPtr hDC);
}
public static void getScreenShot()
{
int windowwidth;
int windowheight;
Bitmap image;
IntPtr windowHandle = Process.GetProcessesByName("firefox")[0].MainWindowHandle;
IntPtr windowDC = Win32Stuff.GetWindowDC(windowHandle);
IntPtr mem = Win32Stuff.CreateCompatibleDC(windowDC);
//need to change this
windowheight = 1920;
windowwidth = 1920;
IntPtr windowImage = Win32Stuff.CreateCompatibleBitmap(windowDC, windowwidth, windowheight);
IntPtr oldBmp = (IntPtr)Win32Stuff.SelectObject(mem, windowImage);
Win32Stuff.BitBlt(mem, 0, 0, windowwidth, windowheight, windowDC, 0, 0, 13369376);
//Win32Stuff.SelectObject(mem, oldBmp);
image = Image.FromHbitmap(mem);
Win32Stuff.DeleteDC(mem);
Win32Stuff.ReleaseDC(windowHandle, mem);
}
我怎么能看到具体的错误是什么,为什么不会Image.FromHbitmap()
输出GDI位图从我的指针?
变化
image = Image.FromHbitmap(mem);
image = Image.FromHbitmap(windowImage);