void GdiPlusScreenCapture(MONITORINFOEX info, IStream* istream)
{
HDC DevC = CreateDC(nullptr, info.szDevice, nullptr, nullptr);
DWORD Width = info.rcMonitor.right - info.rcMonitor.left;
DWORD Height = info.rcMonitor.bottom - info.rcMonitor.top;
HDC CaptureDC = CreateCompatibleDC(DevC);
HBITMAP CaptureBitmap = CreateCompatibleBitmap(DevC, Width, Height);
HGDIOBJ old_obj = SelectObject(CaptureDC, CaptureBitmap);
BitBlt(CaptureDC, 0, 0, Width, Height, DevC, 0, 0, SRCCOPY | CAPTUREBLT);
Gdiplus::Bitmap bitmap(CaptureBitmap, nullptr);
CLSID pngClsid;
CLSIDFromString(L"{557cf401-1a04-11d3-9a73-0000f81ef32e}", &pngClsid);
bitmap.Save(istream, &pngClsid, nullptr);
SelectObject(CaptureDC, old_obj);
DeleteDC(CaptureDC);
ReleaseDC(nullptr, DevC);
DeleteObject(CaptureBitmap);
DeleteDC(DevC);
}
void SaveScreenCapture()
{
std::vector<MONITORINFOEX> monitorInfos;
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);
// get the bitmap handle to the bitmap screenshot
HDC hdc = GetDC(nullptr);
EnumDisplayMonitors(hdc, nullptr, [](HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) -> BOOL {
std::vector<MONITORINFOEX>* pMonData = reinterpret_cast<std::vector<MONITORINFOEX>*>(dwData);
MONITORINFOEX info;
info.cbSize = sizeof(MONITORINFOEX);
GetMonitorInfo(hMonitor, &info);
pMonData->push_back(info);
return true;
}, reinterpret_cast<LPARAM>(&monitorInfos));
int index = 1;
for (auto& monitorInfo : monitorInfos)
{ //Create an empty IStream:
IStream* pIStream = nullptr;
if (CreateStreamOnHGlobal(nullptr, true, &pIStream) == S_OK)
{
GdiPlusScreenCapture(monitorInfo, pIStream);
HGLOBAL hg = nullptr;
GetHGlobalFromStream(pIStream, &hg);
SIZE_T bufsize = GlobalSize(hg);
LPVOID ptr = GlobalLock(hg);
TCHAR jpegFile[MAX_PATH + 1] = { 0 };
_stprintf_s(jpegFile, MAX_PATH, "%d.jpg", index);
//write from memory to file for testing:
std::ofstream fout(jpegFile, std::ios::binary);
fout.write((char*)ptr, bufsize);
fout.close();
pIStream->Release();
GlobalUnlock(hg);
}
}
ReleaseDC(nullptr, hdc);
GdiplusShutdown(gdiplusToken);
}