HDC hScrDC, hMemDC; //屏幕和内存设备描述表
HBITMAP hBitmap, hOldBitmap;//位图句柄
int nX, nY, nX2, nY2; //选定区域坐标
int nWidth, nHeight; //位图宽度和高度
int xScrn, yScrn; //屏幕分辨率
//为屏幕创建设备描述表
hScrDC = CreateDC(L"DISPLAY", NULL, NULL, NULL);
// CPaintDC dc(this);
// hScrDC = dc.GetSafeHdc();
//
// 获得屏幕分辨率
xScrn = GetDeviceCaps(hScrDC, HORZRES);
yScrn = GetDeviceCaps(hScrDC, VERTRES);
// 确保选定区域不为空矩形
if (!lpRect || IsRectEmpty(lpRect))
{
nX = 0;
nY = 0;
nX2 = xScrn;
nY2 = yScrn;
}
else
{
// 获得选定区域坐标
nX = lpRect->left;
nY = lpRect->top;
nX2 = lpRect->right;
nY2 = lpRect->bottom;
//确保选定区域是可见的
if (nX < 0) nX = 0;
if (nY < 0) nY = 0;
if (nX2 > xScrn) nX2 = xScrn;
if (nY2 > yScrn) nY2 = yScrn;
}
nWidth = nX2 - nX;
nHeight = nY2 - nY;
//为屏幕设备描述表创建兼容的内存设备描述表
hMemDC = CreateCompatibleDC(hScrDC);
//创建一个与屏幕设备描述表兼容的位图
hBitmap = CreateCompatibleBitmap (hScrDC, nWidth, nHeight);
//把新位图选到内存设备描述表中
// hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);
// 把屏幕设备描述表拷贝到内存设备描述表中
// BitBlt(hMemDC, 0, 0, nWidth, nHeight,hScrDC, nX, nY, SRCCOPY);
//TextOut(hMemDC,100, 100,L"Rigel",sizeof("Rigel"));
BYTE *lpBitmapBits = NULL;
BITMAPINFO RGB24BitsBITMAPINFO;
ZeroMemory(&RGB24BitsBITMAPINFO, sizeof(BITMAPINFO));
RGB24BitsBITMAPINFO.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
RGB24BitsBITMAPINFO.bmiHeader.biWidth = nWidth;
RGB24BitsBITMAPINFO.bmiHeader.biHeight = nHeight;
RGB24BitsBITMAPINFO.bmiHeader.biPlanes = 1;
RGB24BitsBITMAPINFO.bmiHeader.biBitCount = 24;
//得到屏幕位图的句柄
// hBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
HBITMAP directBmp = CreateDIBSection(hMemDC, (BITMAPINFO*)&RGB24BitsBITMAPINFO,
DIB_RGB_COLORS, (void **)&lpBitmapBits, NULL, 0);
HGDIOBJ previousObject = SelectObject(hMemDC, directBmp);
// copy the screen dc to the memory dc
BitBlt(hMemDC, 0, 0, nWidth, nHeight, hScrDC, nX, nY, 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 + ((nWidth*nHeight)*3); ///3=(24 / 8)
//write into file
FILE *mStream = NULL;
if((mStream = fopen(filename, "wb")))
{
//write bitmap file header
fwrite(&bmBITMAPFILEHEADER, sizeof(BITMAPFILEHEADER), 1, mStream);
//write bitmap info
fwrite(&(RGB24BitsBITMAPINFO.bmiHeader), sizeof(BITMAPINFOHEADER), 1, mStream);
//write bitmap pixels data
fwrite(lpBitmapBits, 3*nWidth*nHeight, 1, mStream);
//close file
fclose(mStream);
}
//清除
DeleteDC(hScrDC);
DeleteDC(hMemDC);