#include<windows.h>
#include<iostream>
using namespace std
;
void Screenbmp(HWND hwnd
, int left
, int top
, int width
, int height
, CHAR
* path
){
HDC sourceDC
= GetWindowDC(hwnd
);
HDC momDC
;
momDC
= ::CreateCompatibleDC(sourceDC
);
HBITMAP memBitmap
;
memBitmap
= ::CreateCompatibleBitmap(sourceDC
, width
, height
);
SelectObject(momDC
, memBitmap
);
BitBlt(momDC
, 0, 0, width
, height
, sourceDC
, left
, top
, SRCCOPY
);
BITMAP bmp
;
GetObject(memBitmap
, sizeof(BITMAP
), &bmp
);
FILE
* fp
;
fopen_s(&fp
, path
, "w+b");
BITMAPFILEHEADER bfh
= { 0 };
bfh
.bfOffBits
= sizeof(BITMAPFILEHEADER
) + sizeof(BITMAPINFOHEADER
);
bfh
.bfSize
= bfh
.bfOffBits
+ bmp
.bmWidthBytes
* bmp
.bmHeight
;
bfh
.bfType
= (WORD
)0x4d42;
BITMAPINFOHEADER bih
= { 0 };
bih
.biBitCount
= bmp
.bmBitsPixel
;
bih
.biCompression
= BI_RGB
;
bih
.biHeight
= bmp
.bmHeight
;
bih
.biPlanes
= 1;
bih
.biSize
= sizeof(BITMAPINFOHEADER
);
bih
.biSizeImage
= bmp
.bmWidthBytes
* bmp
.bmHeight
;
bih
.biWidth
= bmp
.bmWidth
;
fwrite(&bfh
, 1, sizeof(BITMAPFILEHEADER
), fp
);
fwrite(&bih
, 1, sizeof(BITMAPINFOHEADER
), fp
);
byte
* p
= new byte
[bmp
.bmWidthBytes
* bmp
.bmHeight
];
GetDIBits(memDC
, (HBITMAP
)memBitmap
, 0, height
, p
,
(LPBITMAPINFO
)&bih
, DIB_RGB_COLORS
);
fwrite(p
, 1, bmp
.bmWidthBytes
* bmp
.bmHeight
, fp
);
delete[] p
;
fclose(fp
);
DeleteObject(memBitmap
);
DeleteDC(momDC
);
ReleaseDC(hwnd
, sourceDC
);
}
本次是使用bitblt来进行截图。BitBlt方法只能抓图普通窗口的截图,对于使用D3D渲染的窗口(例如谷歌、Excel等)则只能获取黑屏。而且需要截图的窗口必须没有最小化,如果最小化,那么截取的也只能是黑屏 如果真的需要截取这些黑屏的窗口,那么可以使用GetDesktopWindow()获得整个桌面的句柄,然后使用SetForegroundWindow将窗口置于顶层,再使用GetWindowRect获得窗口具体位置,再使用BitBlt截图。
转载请注明原文地址:https://ipadbbs.8miu.com/read-25048.html