截屏过程中发现 有的程序后台截屏可以 有的程序截屏就是纯黑色的图形,请找下原因指导
同样的代码 。
#include <windows.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <fstream>
#include <string>
bool SaveMatAsBMP(const cv::Mat& img, const std::string& fileName)
{
try {
cv::imwrite(fileName, img);
return true;
}
catch (const cv::Exception& e) {
std::cerr << "Error saving image: " << e.what() << std::endl;
return false;
}
}
cv::Mat CaptureWindow(HWND hWnd, HDC hWindowDC, HDC hMemoryDC, HBITMAP hBitmap, int width, int height)
{
SelectObject(hMemoryDC, hBitmap);
BitBlt(hMemoryDC, 0, 0, width, height, hWindowDC, 0, 0, SRCCOPY);
cv::Mat img(height, width, CV_8UC3);
BITMAPINFO bmi = { 0 };
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = width;
bmi.bmiHeader.biHeight = -height; // 注意高度是负数,表示从底部开始绘制
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 24;
bmi.bmiHeader.biCompression = BI_RGB;
GetDIBits(hMemoryDC, hBitmap, 0, height, img.data, &bmi, DIB_RGB_COLORS);
return img;
}
int main() {
HWND hWndTarget = FindWindow(L"UnrealWindow", NULL); // 替换为你想要截图的窗口标题
if (hWndTarget == NULL) {
std::cerr << "Unable to find the target window." << std::endl;
return -1;
}
// 创建设备上下文和位图资源
HDC hWindowDC = GetDC(hWndTarget);
HDC hMemoryDC = CreateCompatibleDC(hWindowDC);
RECT windowRect;
GetWindowRect(hWndTarget, &windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
HBITMAP hBitmap = CreateCompatibleBitmap(hWindowDC, width, height);
HGDIOBJ oldBitmap = SelectObject(hMemoryDC, hBitmap);
Sleep(3000);
int numIterations = 10; // 替换成您期望的循环次数
for (int i = 0; i < numIterations; ++i)
{
cv::Mat screenshot = CaptureWindow(hWndTarget, hWindowDC, hMemoryDC, hBitmap, width, height);
std::string outputFileName = "screenshot_" + std::to_string(i) + ".bmp";
if (!SaveMatAsBMP(screenshot, outputFileName)) {
std::cerr << "Failed to save screenshot " << i << std::endl;
// 可能需要提前结束程序或执行其他恢复逻辑
}
Sleep(1000);
}
// 清理资源
SelectObject(hMemoryDC, oldBitmap);
DeleteObject(hBitmap);
DeleteDC(hMemoryDC);
ReleaseDC(hWndTarget, hWindowDC);
return 0;
}
黑屏图形如下:
正常截屏如下: