問題:如何用C程式語言擷取全螢幕,並輸出成BMP檔案? 請別回答按下Print Scr XD!
解答: void CaptureFullWindow(void) { HDC hScrDC,
hMemDC; int width, height;
//the pointer will
save all pixel point's color value BYTE *lpBitmapBits = NULL;
//creates a device context for the screen device hScrDC =
CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
//get the screen
point size width = GetDeviceCaps(hScrDC, HORZRES); height =
GetDeviceCaps(hScrDC, VERTRES);
//creates a memory device
context (DC) compatible with the screen device(hScrDC) hMemDC =
CreateCompatibleDC(hScrDC);
//initialise the struct
BITMAPINFO for the bimap infomation, //in order to use the
function CreateDIBSection // on wince os, each pixel stored by
24 bits(biBitCount=24) //and no compressing(biCompression=0)
BITMAPINFO RGB24BitsBITMAPINFO;
ZeroMemory(&RGB24BitsBITMAPINFO, sizeof(BITMAPINFO));
RGB24BitsBITMAPINFO.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
RGB24BitsBITMAPINFO.bmiHeader.biWidth = width;
RGB24BitsBITMAPINFO.bmiHeader.biHeight = height;
RGB24BitsBITMAPINFO.bmiHeader.biPlanes = 1;
RGB24BitsBITMAPINFO.bmiHeader.biBitCount = 24; //use the function
CreateDIBSection and SelectObject //in order to get the bimap
pointer : lpBitmapBits HBITMAP hBitmap = CreateDIBSection(hMemDC,
(BITMAPINFO*)&RGB24BitsBITMAPINFO, DIB_RGB_COLORS, (void
**)&lpBitmapBits, NULL, 0); HGDIOBJ hOldBitmap =
SelectObject(hMemDC, hBitmap);
// copy the screen dc to the
memory dc BitBlt(hMemDC, 0, 0, width, height, hScrDC, 0, 0,
SRCCOPY); //if you only want to get the every pixel color value,
//you can begin here and the following part of this function will be
unuseful; //the following part is in order to write file;
//bimap file header in order to write bmp file
BITMAPFILEHEADER bmBITMAPFILEHEADER;
ZeroMemory(&bmBITMAPFILEHEADER, sizeof(BITMAPFILEHEADER));
bmBITMAPFILEHEADER.bfType = 0x4d42; //bmp
bmBITMAPFILEHEADER.bfOffBits = sizeof(BITMAPFILEHEADER) +
sizeof(BITMAPINFOHEADER); bmBITMAPFILEHEADER.bfSize =
bmBITMAPFILEHEADER.bfOffBits + ((width*height)*3); ///3=(24 / 8)
DWORD dwNumBytes;
HANDLE hFile = CreateFile( L"\\Storage
Card\\capture.bmp", GENERIC_WRITE,
(DWORD) 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE) return ;
WriteFile(hFile, &bmBITMAPFILEHEADER, sizeof(BITMAPFILEHEADER),
&dwNumBytes, NULL); // Write the file header WriteFile(hFile,
&(RGB24BitsBITMAPINFO.bmiHeader), sizeof(BITMAPINFOHEADER),
&dwNumBytes, NULL); // Write the DIB header WriteFile(hFile,
lpBitmapBits, 3*width*height, &dwNumBytes, NULL); //Write DIB bits
FlushFileBuffers(hFile);
CloseHandle(hFile);
//delete DeleteObject(hMemDC); DeleteObject(hScrDC);
DeleteObject(hBitmap); DeleteObject(hOldBitmap); }
|