#include <windows.h>
#include <gdiplus.h>
//use cstring
#include <atlstr.h>
#pragma comment(lib, "gdiplus.lib")
using namespace Gdiplus;
int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
UINT num = 0; // number of image encoders
UINT size = 0; // size of the image encoder array in bytes
ImageCodecInfo* pImageCodecInfo = NULL;
Gdiplus::GetImageEncodersSize(&num, &size);
if (size == 0)
return -1; // Failure
pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
if (pImageCodecInfo == NULL)
return -1; // Failure
Gdiplus::GetImageEncoders(num, size, pImageCodecInfo);
for (UINT j = 0; j < num; ++j)
{
if (wcscmp(pImageCodecInfo[j].MimeType, format) == 0)
{
*pClsid = pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
return j; // Success
}
}
free(pImageCodecInfo);
return -1; // Failure
}
void CaptureScreen()
{
int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
HWND hDesktopWnd = GetDesktopWindow();
HDC hDesktopDC = GetDC(hDesktopWnd);
HDC hCaptureDC = CreateCompatibleDC(hDesktopDC);
HBITMAP hCaptureBitmap = CreateCompatibleBitmap(hDesktopDC, nScreenWidth, nScreenHeight);
SelectObject(hCaptureDC, hCaptureBitmap);
BitBlt(hCaptureDC, 0, 0, nScreenWidth, nScreenHeight, hDesktopDC, 0, 0, SRCCOPY);
//保存
//初始化GDI
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
if (Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL) != Ok)
{
;
}
SYSTEMTIME Systime;
GetLocalTime(&Systime);
CString szFileName;
szFileName.Format(L"%u-%u-%u-%02u%02u.png",
Systime.wYear, Systime.wMonth, Systime.wDay, Systime.wHour, Systime.wMinute);
CLSID pngClsid;
GetEncoderClsid(L"image/png", &pngClsid);
Gdiplus::Bitmap *pbmSrc = Gdiplus::Bitmap::FromHBITMAP(hCaptureBitmap, NULL);
if (pbmSrc->Save(szFileName, &pngClsid) == Ok) {
;
}
//卸载GDI
Gdiplus::GdiplusShutdown(gdiplusToken);
DeleteObject(hCaptureBitmap);
ReleaseDC(hDesktopWnd, hDesktopDC);
DeleteDC(hCaptureDC);
}
int main()
{
CaptureScreen();
return 0;
}
还没有评论,来说两句吧...