C++ realize screen capture function
- 2020-06-07 04:55:32
- OfStack
This article shares the specific code of C++ to realize the full-screen screenshot function for your reference. The specific content is as follows
Recently maintained projects, in some cases, just having a log is not enough, so added screenshots, in certain cases, automatic screenshots to aid analysis, to improve the program. Below is the screenshot implementation code.
void CDemoDlg::ScreenShot(void)
{
CWnd *pDesktop = GetDesktopWindow();
CDC *pdeskdc = pDesktop->GetDC();
CRect re;
// Gets the size of the window
pDesktop->GetClientRect(&re);
CBitmap bmp;
bmp.CreateCompatibleBitmap(pdeskdc, re.Width(), re.Height());
// create 1 A compatible memory artboard
CDC memorydc;
memorydc.CreateCompatibleDC(pdeskdc);
// Select the brush
CBitmap *pold = memorydc.SelectObject(&bmp);
// The plot
memorydc.BitBlt(0, 0, re.Width(), re.Height(), pdeskdc, 0, 0, SRCCOPY);
// Gets the mouse position, and then adds the mouse image
CPoint po;
GetCursorPos(&po);
HICON hinco = (HICON)GetCursor();
memorydc.DrawIcon(po.x - 10, po.y - 10, hinco);
// Select the original brush
memorydc.SelectObject(pold);
BITMAP bit;
bmp.GetBitmap(&bit);
// define Image size (unit: byte )
DWORD size = bit.bmWidthBytes * bit.bmHeight;
LPSTR lpdata = (LPSTR)GlobalAlloc(GPTR, size);
// And then create 1 a bmp The required file header for a file
BITMAPINFOHEADER pbitinfo;
pbitinfo.biBitCount = 24;
pbitinfo.biClrImportant = 0;
pbitinfo.biCompression = BI_RGB;
pbitinfo.biHeight = bit.bmHeight;
pbitinfo.biPlanes = 1;
pbitinfo.biSize = sizeof(BITMAPINFOHEADER);
pbitinfo.biSizeImage = size;
pbitinfo.biWidth = bit.bmWidth;
pbitinfo.biXPelsPerMeter = 0;
pbitinfo.biYPelsPerMeter = 0;
GetDIBits(pdeskdc->m_hDC, bmp, 0, pbitinfo.biHeight, lpdata, (BITMAPINFO*)
&pbitinfo, DIB_RGB_COLORS);
BITMAPFILEHEADER bfh;
bfh.bfReserved1 = bfh.bfReserved2 = 0;
bfh.bfType = ((WORD)('M' << 8) | 'B');
bfh.bfSize = size + 54;
bfh.bfOffBits = 54;
// Written to the file
CFile file;
CString strFileName(GetAppPathW().c_str());
strFileName += _T("ScreenShot\\");
CreateDirectory((LPCTSTR)strFileName, NULL);
CTime t = CTime::GetCurrentTime();
CString tt = t.Format("%Y-%m-%d_%H-%M-%S");
strFileName += tt;
strFileName += _T(".bmp");
if (file.Open((LPCTSTR)strFileName, CFile::modeCreate | CFile::modeWrite))
{
file.Write(&bfh, sizeof(BITMAPFILEHEADER));
file.Write(&pbitinfo, sizeof(BITMAPINFOHEADER));
file.Write(lpdata, size);
file.Close();
}
GlobalFree(lpdata);
}
Code comments detailed, I will not say what, save as bmp lossless file, the volume will be a little big, friends can be converted to png format to save oh.