自己寫遠端控制軟體之捕捉螢幕

LiuYinChina發表於2013-01-31
函式說明:
        為保證影象質量,用 24 位點陣圖,後面再說如何壓縮成 JPG

函式如下:
void CaptureScreen(PCHAR lpBuffer, DWORD dwLength, DWORD dwWidth, DWORD dwHeight, DWORD &dwBitmapSize);

lpBuffer 儲存以下資訊:
BITMAPFILEHEADER
BITMAPINFOHEADER
RGB 資料


void CaptureScreen(PCHAR lpBuffer, DWORD dwLength, DWORD dwWidth, DWORD dwHeight, DWORD &dwBitmapSize)
{
	dwBitmapSize = 0;

	HWND hDesktopWnd= ::GetDesktopWindow();
	HDC hDesktopDC	= ::GetDC(hDesktopWnd);
	HDC hCaptureDC	= ::CreateCompatibleDC(hDesktopDC);
	HBITMAP hBitmap = ::CreateCompatibleBitmap(hDesktopDC, dwWidth, dwHeight);
	LPBITMAPFILEHEADER pFileHeader= (LPBITMAPFILEHEADER) lpBuffer;
	LPBITMAPINFO pBitmapInfo = (LPBITMAPINFO) (lpBuffer + sizeof(BITMAPFILEHEADER));

	::SelectObject(hCaptureDC, hBitmap);
	::BitBlt(hCaptureDC, 0, 0, dwWidth, dwHeight, hDesktopDC, 0, 0, SRCCOPY);

	BITMAP bmpBit = { 0 };
	::GetObject(hBitmap, sizeof(BITMAP), &bmpBit);

	pBitmapInfo->bmiHeader.biSize		= sizeof(BITMAPINFOHEADER);
	pBitmapInfo->bmiHeader.biWidth		= bmpBit.bmWidth;
	pBitmapInfo->bmiHeader.biHeight		= bmpBit.bmHeight;
	pBitmapInfo->bmiHeader.biPlanes		= 1;
	pBitmapInfo->bmiHeader.biBitCount	= 24;
	pBitmapInfo->bmiHeader.biCompression	= 0;
	pBitmapInfo->bmiHeader.biSizeImage	= bmpBit.bmWidthBytes * bmpBit.bmHeight;
	pBitmapInfo->bmiHeader.biXPelsPerMeter= 0;
	pBitmapInfo->bmiHeader.biYPelsPerMeter= 0;
	pBitmapInfo->bmiHeader.biClrUsed	= 0;
	pBitmapInfo->bmiHeader.biClrImportant	= 0;

	pFileHeader->bfType	= 0x4D42;
	pFileHeader->bfOffBits	= sizeof(BITMAPINFOHEADER) + sizeof(BITMAPFILEHEADER);
	pFileHeader->bfSize	= pBitmapInfo->bmiHeader.biSizeImage + pFileHeader->bfOffBits;
	pFileHeader->bfReserved1= 0;
	pFileHeader->bfReserved2= 0;

	PCHAR pBmpData = lpBuffer + sizeof(BITMAPINFOHEADER) + sizeof(BITMAPFILEHEADER);
	::GetDIBits(hCaptureDC, hBitmap, 0, bmpBit.bmHeight, pBmpData, pBitmapInfo, DIB_RGB_COLORS);

	::ReleaseDC(hDesktopWnd, hDesktopDC);
	::DeleteDC(hCaptureDC);
	::DeleteObject(hBitmap);

	dwBitmapSize = sizeof(BITMAPINFOHEADER) + sizeof(BITMAPFILEHEADER) + pBitmapInfo->bmiHeader.biSizeImage;
}



相關文章