Hello you guys. I'm working a bit on improving my C++ so I decided to mess around with screenshots. it's windows based an uses gdiplus and windows api. It gets your window with the windows api then handles the bitmap that it generates with gdiplus and saves it to a file.
The screenshot header file
#include <Windows.h>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
#pragma once
class Screenshot
{
public:
Screenshot();
~Screenshot();
void makeScreenshot(const WCHAR*);
private:
ULONG_PTR token;
int GetEncoderClsid(const WCHAR*, CLSID*);
};
The screenshot class
#include "Screenshot.h"
ULONG_PTR gdiToken;
Screenshot::Screenshot()
{
Gdiplus::GdiplusStartupInput StartupInput;
Gdiplus::GdiplusStartup(&gdiToken, &StartupInput, NULL);
}
Screenshot::~Screenshot()
{
Gdiplus::GdiplusShutdown(gdiToken);
}
int Screenshot::GetEncoderClsid(const WCHAR* format, CLSID* pClsid) {
UINT num = 0;
UINT size = 0;
Gdiplus::ImageCodecInfo* pImageCodecInfo = NULL;
Gdiplus::GetImageEncodersSize(&num, &size);
if (size == 0)
return -1;
pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size));
if (pImageCodecInfo == NULL)
return -1;
Gdiplus::GetImageEncoders(num, size, pImageCodecInfo);
for (UINT codec = 0; codec < num; ++codec)
{
if (wcscmp(pImageCodecInfo[codec].MimeType, format) == 0)
{
*pClsid = pImageCodecInfo[codec].Clsid;
free(pImageCodecInfo);
return codec;
}
}
free(pImageCodecInfo);
return -1;
}
void Screenshot::makeScreenshot(const WCHAR* filename) {
int screenHeight = GetSystemMetrics(SM_CYSCREEN);
int screenWidth = GetSystemMetrics(SM_CXSCREEN);
HWND desktopWindow = GetDesktopWindow();
HDC desktopDC = GetDC(desktopWindow);
HDC captureDC = CreateCompatibleDC(desktopDC);
HBITMAP captureBitmap = CreateCompatibleBitmap(desktopDC, screenWidth, screenHeight);
SelectObject(captureDC, captureBitmap);
BitBlt(captureDC, 0, 0, screenWidth, screenHeight, desktopDC, 0, 0, SRCCOPY | CAPTUREBLT);
Gdiplus::Bitmap *bitmap = new Gdiplus::Bitmap(captureBitmap, NULL);
CLSID clsId;
int retVal = this->GetEncoderClsid(L"image/png", &clsId);
bitmap->Save(filename, &clsId, NULL);
ReleaseDC(desktopWindow, desktopDC);
DeleteDC(captureDC);
DeleteObject(captureBitmap);
}