DC Screenshot on WinCE device and saving into bmp file using C++

There is something which i have discovered during my application development on Wince platform. Taking screenshot of DC using c++ windows programming. Here below is the small code snippet to take snapshot of display screen  and saving the file into bmp.

int TakeScreenShot()
{
        HDC memdc;
DWORD  dwWidth, dwHeight, dwNumColors, dwBPP, ColorSize;
void *pBits;
HBITMAP hbmp;
BITMAPFILEHEADER fileheader;
BITMAPINFOHEADER infoheader;
RGBQUAD colors[256];
BITMAPINFO bmpinfo;
HGDIOBJ hret;
///TBD
FILE* bmpfp;
bmpfp = fopen(("test.bmp"),"wb");
dwWidth = GetDeviceCaps(hdc, HORZRES);
dwHeight = GetDeviceCaps(hdc, VERTRES);
dwBPP = GetDeviceCaps(hdc, BITSPIXEL);
if (dwBPP <= 8)
{
dwNumColors = 256;
}
else 
{
dwNumColors = 0;
}
if (!(memdc = CreateCompatibleDC(hdc)))
{
return (0);
//AfxMessageBox(L"Creaegt compatibl dc failed");
}
bmpinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmpinfo.bmiHeader.biWidth = dwWidth;
bmpinfo.bmiHeader.biHeight = dwHeight;
bmpinfo.bmiHeader.biPlanes = 1;
bmpinfo.bmiHeader.biBitCount = (WORD)dwBPP;
bmpinfo.bmiHeader.biCompression = BI_RGB;
bmpinfo.bmiHeader.biSizeImage = 0;
bmpinfo.bmiHeader.biXPelsPerMeter = 0;
bmpinfo.bmiHeader.biYPelsPerMeter = 0;
bmpinfo.bmiHeader.biClrUsed = dwNumColors;
bmpinfo.bmiHeader.biClrImportant = dwNumColors;
if(!hdc)
{
//AfxMessageBox(L"hdc failed");
}

hbmp = CreateDIBSection(hdc, &bmpinfo, DIB_RGB_COLORS, &pBits, NULL, 0);
if (!hbmp)
{
DeleteDC(memdc);
return (0);
}
hret = SelectObject(memdc, hbmp);
if (!BitBlt(memdc, 0, 0, dwWidth, dwHeight, hdc, 0, 0, SRCCOPY))
{
DeleteDC(memdc);
//AfxMessageBox(L"BitBlt spates fail");
return (0);
}
if (dwNumColors)
dwNumColors = GetDIBColorTable(memdc, 0, dwNumColors, colors);

fileheader.bfType = 0x4D42;
ColorSize = dwNumColors * sizeof(RGBQUAD);
fileheader.bfSize = ((dwWidth*dwHeight*dwBPP) >> 3) + ColorSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
fileheader.bfReserved1 = fileheader.bfReserved2 = 0;
fileheader.bfOffBits = ColorSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
infoheader.biSize = sizeof(BITMAPINFOHEADER);
infoheader.biWidth = dwWidth;
infoheader.biHeight = dwHeight;
infoheader.biPlanes = 1;
infoheader.biBitCount = (WORD)dwBPP;
infoheader.biCompression = BI_RGB;
infoheader.biSizeImage = infoheader.biClrImportant = 0;
infoheader.biXPelsPerMeter = infoheader.biYPelsPerMeter = 0;
infoheader.biClrUsed = dwNumColors;

fwrite(&fileheader, sizeof(BITMAPFILEHEADER),1,bmpfp);
fwrite(&infoheader, sizeof(BITMAPINFOHEADER),1,bmpfp);

if (!dwNumColors)
fwrite(colors, ColorSize,1, bmpfp);

ColorSize = (dwWidth * dwHeight * dwBPP) >> 3;
fwrite(pBits, ColorSize,1, bmpfp);

fclose(bmpfp);
DeleteObject(hbmp);
DeleteDC(memdc); 
        return (1);
}

1 comment: