19,468
社区成员
发帖
与我相关
我的任务
分享
void SaveScreen(LPCTSTR lpszFilePath)
{
TCHAR szPath[MAX_PATH] = {0};
if(NULL == lpszFilePath)
{
GetModuleFileName(NULL, szPath, MAX_PATH-1);
LPTSTR lpszPath = _tcschr(szPath, _T('\\'));
LPTSTR lpszEnd = szPath;
while(NULL != lpszPath)
{
lpszEnd = lpszPath;
lpszPath = _tcschr(lpszPath+1, _T('\\'));
}
int nPos = lpszEnd - szPath + 1;
szPath[nPos] = _T('\0');
CString strPath(szPath);
LPCTSTR lpszFile = _T("PICTURES");
strPath += lpszFile;
if(!PathFileExists(strPath))
{
if(CreateDirectory(strPath, NULL))
{
return ;
}
}
_stprintf_s(_tcschr(szPath, _T('\0')), _countof(szPath) - _tcslen(szPath), _T("%s\\CS_%05d.bmp"), lpszFile, ++m_nIndex);
}
else
{
_stprintf_s(szPath, sizeof(szPath), _T("%s"), lpszFilePath);
}
if(0 != _tcslen(szPath))
{
CDC* pDC = CDC::FromHandle(::GetDC(NULL));
int nBitsPixel = pDC->GetDeviceCaps(BITSPIXEL);
int nWidth = pDC->GetDeviceCaps(HORZRES);
int nHeight = pDC->GetDeviceCaps(VERTRES);
CDC memDC;
memDC.CreateCompatibleDC(pDC);
CBitmap bitmap;
bitmap.CreateCompatibleBitmap(pDC, nWidth, nHeight);
CBitmap* oldBmp = memDC.SelectObject(&bitmap);
memDC.BitBlt(0, 0, nWidth, nHeight, pDC, 0, 0, SRCCOPY);
BITMAP bmp;
bitmap.GetBitmap(&bmp);
try
{
CFile file;
file.Open(szPath, CFile::modeCreate | CFile::typeBinary | CFile::modeWrite);
BITMAPINFOHEADER bih = {0};
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biBitCount = bmp.bmBitsPixel;
bih.biCompression = BI_RGB;
bih.biHeight = bmp.bmHeight;
bih.biPlanes = 1;
bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;
bih.biWidth = bmp.bmWidth;
BITMAPFILEHEADER bfh = {0};
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;
bfh.bfType = (WORD)0x4d42;
file.Write(&bfh, sizeof(BITMAPFILEHEADER));
file.Write(&bih, sizeof(BITMAPINFOHEADER));
BYTE* pByte = new BYTE[bmp.bmWidthBytes * bmp.bmHeight];
GetDIBits(memDC.m_hDC, (HBITMAP)bitmap.m_hObject, 0, nHeight, pByte, (LPBITMAPINFO)&bih, DIB_RGB_COLORS);
file.Write(pByte, bmp.bmWidthBytes * bmp.bmHeight);
file.Flush();
file.Close();
delete[] pByte;
}
catch (CFileException* e)
{
e->ReportError();
e->Delete();
}
memDC.SelectObject(oldBmp);
bitmap.DeleteObject();
memDC.DeleteDC();
}
}