屏幕截图代码
//截图
INT CAnimationHelper::_GetScreenShotData( HWND hWnd, LPRECT rcShot, BYTE ** ppBuf ) { //截图 HDC hDcWnd = NULL; if (hWnd) { hDcWnd = ::GetDC(hWnd); } else { HWND hWndDesk = ::GetDesktopWindow(); hDcWnd = ::GetDC(hWndDesk); } WORD nBitPerPixel = (WORD)::GetDeviceCaps(hDcWnd, BITSPIXEL); INT nWidth = rcShot->right-rcShot->left; INT nHeight = rcShot->bottom-rcShot->top; INT nOffset = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); DWORD dwSize = nBitPerPixel*nWidth*nHeight + nOffset; *ppBuf = new BYTE[dwSize]; HDC hDcMem = ::CreateCompatibleDC(hDcWnd); HBITMAP hBmpMem = ::CreateCompatibleBitmap(hDcWnd, nWidth, nHeight); HBITMAP hBmpOld = (HBITMAP)::SelectObject(hDcMem, hBmpMem); ::BitBlt(hDcMem, 0, 0, nWidth, nHeight, hDcWnd, rcShot->left, rcShot->top, SRCCOPY);
BITMAPINFO bih = {0}; bih.bmiHeader.biBitCount = nBitPerPixel; bih.bmiHeader.biCompression = BI_RGB; bih.bmiHeader.biHeight = nHeight; bih.bmiHeader.biPlanes = 1; bih.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bih.bmiHeader.biSizeImage = nBitPerPixel*nWidth*nHeight; bih.bmiHeader.biWidth = nWidth;
BITMAPFILEHEADER bfh = {0}; bfh.bfOffBits = nOffset; bfh.bfSize = dwSize; bfh.bfType = (WORD)0x4d42;
memcpy(*ppBuf, &bfh, sizeof(BITMAPFILEHEADER)); memcpy((*ppBuf)+sizeof(BITMAPFILEHEADER), &bih.bmiHeader, sizeof(BITMAPINFOHEADER));
::GetDIBits(hDcMem, hBmpMem, 0, nHeight, (*ppBuf)+nOffset, &bih, DIB_RGB_COLORS);
if (nBitPerPixel==32) { BYTE *pData = (*ppBuf)+nOffset+3; for (INT i=0; i<nHeight; i++) { for (INT j = 0; j<nWidth; j++) { *pData = 0xFF; pData += 4; } } }
//for test // FILE *fp = _wfopen(L"E:\\a.bmp", L"w+b"); // fwrite(*ppBuf, 1, dwSize, fp);//写入位图数据 // fclose(fp);
::SelectObject(hDcMem, hBmpOld); ::DeleteObject(hBmpMem); ::DeleteObject(hDcMem); ::ReleaseDC(hWnd,hDcWnd);
return dwSize; }