在VC6.0下测试通过
// TODO: Add your control notification handler code here
//CString str;
//m_FlashPlayer.Zoom(250);
CDC* pDeskDC = GetDesktopWindow()->GetDC(); //获取桌面画布对象
CRect rc;
GetDesktopWindow()->GetClientRect(rc); //获取屏幕的客户区域
CDC memDC; //定义一个内存画布
memDC.CreateCompatibleDC(pDeskDC); //创建一个兼容的画布
CBitmap bmp;
bmp.CreateCompatibleBitmap(pDeskDC,rc.Width(),rc.Height()); //创建与桌面兼容位图对象,与目前在该设备上下文选择位图的格式相同
memDC.SelectObject(&bmp); //选中位图对象
// m_X = m_RecvX;
// m_Y = m_RecvY;
memDC.BitBlt(0,0,rc.Width(),rc.Height(),pDeskDC,0,0,SRCCOPY);//复制一个从源设备上下文位图到当前设备上下文,在此主要是确定复制位图的大小
BITMAP bitmap;
bmp.GetBitmap(&bitmap);//调用此成员函数来检索有关一个CBitmap对象的信息
GetDeviceCaps(pDeskDC->m_hDC, PLANES);
//下面要把DDB变成DIB
int panelsize = 0; //记录调色板大小
if (bitmap.bmBitsPixel<16) //判断是否为真彩色位图
panelsize = (pow(2,bitmap.bmBitsPixel)*sizeof(RGBQUAD));//计算2的bitmap.bmBitsPixel*sizeof(RGBQUAD)次幂
BITMAPINFO *pBInfo = (BITMAPINFO*)LocalAlloc(LPTR,sizeof(BITMAPINFOHEADER)+panelsize);
pBInfo->bmiHeader.biBitCount = bitmap.bmBitsPixel;//每位像素用几位来显示/当前显示分辨率下每个像素所占字节数(调色板的数目)
pBInfo->bmiHeader.biClrImportant = 0;//指定颜色的索引数量是用于显示位图需要。如果这个值是零,所有颜色都需要
pBInfo->bmiHeader.biCompression = BI_RGB;//压缩类型
pBInfo->bmiHeader.biHeight = rc.Height();
pBInfo->bmiHeader.biPlanes = 1;//指定目标设备的数位面
pBInfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pBInfo->bmiHeader.biSizeImage = bitmap.bmWidthBytes*bitmap.bmHeight;//指定图像的字节大小:每行字节*高度
pBInfo->bmiHeader.biWidth = rc.Width();
pBInfo->bmiHeader.biXPelsPerMeter = 0;
pBInfo->bmiHeader.biYPelsPerMeter = 0;
pBInfo->bmiHeader.biClrUsed=0;
char* pData = new char[bitmap.bmWidthBytes* bitmap.bmHeight];//位图的数据大小,用来存放数据
::GetDIBits(memDC.m_hDC,bmp,0,bitmap.bmHeight,pData,pBInfo,DIB_RGB_COLORS);//把位图数据放到上面的指针指向的地方
int BufSize = panelsize+ sizeof(BITMAPINFOHEADER)+bitmap.bmWidthBytes* bitmap.bmHeight;//DIB(设备无关位图)的组成
BITMAPFILEHEADER bmpfileheader;
HANDLE had=CreateFile("e:\\abc.bmp",GENERIC_WRITE,0,NULL,CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,NULL);
if (had==INVALID_HANDLE_VALUE)
AfxMessageBox("创建文件失败");
bmpfileheader.bfType=0x4D42;
bmpfileheader.bfSize=BufSize+54;
bmpfileheader.bfReserved1=0;
bmpfileheader.bfReserved2=0;
bmpfileheader.bfOffBits=54;
DWORD write;
WriteFile(had,(LPSTR)&bmpfileheader,sizeof(BITMAPFILEHEADER),&write,NULL);
WriteFile(had,(LPSTR)pBInfo,sizeof(BITMAPINFOHEADER)+panelsize,&write,NULL);
WriteFile(had,(LPSTR)pData,bitmap.bmWidthBytes* bitmap.bmHeight,&write,NULL);
delete[] pData;
LocalFree(pBInfo);
pDeskDC->DeleteDC();
bmp.DeleteObject();
memDC.DeleteDC();
CloseHandle(had);
//最后没有调用FlushFileBuffers、CloseHandle来刷新BUF,关闭文件~~
//不然,程序不关闭的话,不能打开图片,也不能再截图
// AfxMessageBox(str);