在Windows中截取屏幕将输出黑屏图像

我正在尝试在 Windows 中截取整页屏幕截图。函数在第一次调用时工作,但在第二次调用后根本不起作用,它只是得到一个大小稳定的黑屏图像。当我使用调试器时,该功能运行良好而不会出现黑屏。

这是代码:

void screenshot(std::string imageaPath)
{
    ULONG_PTR gdiplustoken;
    Gdiplus::GdiplusStartupInput gdistartupinput;
    Gdiplus::GdiplusStartupOutput gdistartupoutput;

    gdistartupinput.SuppressBackgroundThread = true;
    GdiplusStartup(&gdiplustoken, &gdistartupinput, &gdistartupoutput); //start GDI+

    HDC hScreenDC = GetDC(GetDesktopWindow());
    HDC hMemoryDC = CreateCompatibleDC(hScreenDC);

    int cx = GetSystemMetrics(SM_CXVIRTUALSCREEN);
    int cy = GetSystemMetrics(SM_CYVIRTUALSCREEN);
    int x = GetSystemMetrics(SM_XVIRTUALSCREEN); 
    int y = GetSystemMetrics(SM_YVIRTUALSCREEN);

    HBITMAP hbitmap = CreateCompatibleBitmap(hScreenDC, cx, cy);
    HBITMAP holdbitmap = static_cast<HBITMAP>(SelectObject(hMemoryDC, hbitmap));

    BitBlt(hMemoryDC, 0, 0, cx, cy, hScreenDC, x, y, SRCCOPY | CAPTUREBLT);
    hbitmap = static_cast<HBITMAP>(SelectObject(hMemoryDC, holdbitmap));    

    UINT num, size;

    Gdiplus::ImageCodecInfo* imagecodecinfo;
    Gdiplus::GetImageEncodersSize(&num, &size); // get count of codec

    imagecodecinfo = (Gdiplus::ImageCodecInfo*)(malloc(size));
    GetImageEncoders(num, size, imagecodecinfo);//get codec

    CLSID clsidEncoder;

    for (int i = 0; i < num; i++)
    {
        if (wcscmp(imagecodecinfo[i].MimeType, L"image/jpeg") == 0)
            clsidEncoder = imagecodecinfo[i].Clsid; // get jpeg codec id
    }

    free(imagecodecinfo);
    Gdiplus::Bitmap* bm = new Gdiplus::Bitmap(hbitmap, NULL);
    std::wstring ws;
    ws.assign(imageaPath.begin(), imageaPath.end());//sring to wstring
    bm->Save(ws.c_str(), &clsidEncoder); //save in jpeg format
    SelectObject(hMemoryDC, holdbitmap);//Release Objects
    DeleteObject(hMemoryDC);
    DeleteObject(hbitmap);
    ReleaseDC(GetDesktopWindow(), hScreenDC);

    Gdiplus::GdiplusShutdown(gdiplustoken);
}

更新:

好的,当我system("pause");用来使程序停止时,当按 Enter 使程序继续时,我找到了一种没有黑屏图像的截屏方法,它正在工作,我使用了 c++ sleep 方法但不起作用,知道吗?

...
HBITMAP holdbitmap = static_cast<HBITMAP>(SelectObject(hMemoryDC, hbitmap));

system("pause");

BitBlt(hMemoryDC, 0, 0, cx, cy, hScreenDC, x, y, SRCCOPY | CAPTUREBLT);
...

睡眠方法:

Sleep(1000);
std::this_thread::sleep_for(std::chrono::seconds(1));

更新2:

我正在使用 curl 发送屏幕截图请求,我正在服务器(rdp)中进行测试,当我发送请求时我已注销,我认为服务器中的睡眠模式已启用,当我注销时,服务器将处于睡眠状态,就像计算机一样屏幕变暗,这就是为什么 BitBlt() 失败并且 GetLastError() 将返回 5,这意味着访问被拒绝

回答

的文档GdiplusShutdown

你必须调用GdiplusStartup你创建的任何GDI +对象面前,你必须删除所有的GDI +的对象(或让他们走出去的范围),在打电话前GdiplusShutdown

您正在泄漏bm = new Gdiplus::Bitmap(...),这违反了此规则。


以上是在Windows中截取屏幕将输出黑屏图像的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>