可能用到的库:
#include <afxwin.h>
#include <windows.h>
代码:
void CScreenShotDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
//CClientDC dc(this);//只截对话框,用这句
HWND hwnd = ::GetDesktopWindow();//截整个屏幕,用从这往下4句
HDC hdc = ::GetDC(hwnd);
CDC dc;
dc.Attach(hdc);
CRect rc;
//GetClientRect(&rc);//只截对话框,用这句
rc.SetRect(0,0, GetSystemMetrics( SM_CXSCREEN ), GetSystemMetrics( SM_CYSCREEN ));//截整个屏幕,用这句
int iBitPerPixel = dc.GetDeviceCaps(BITSPIXEL);
int iWidth = rc.Width();
int iHeight = rc.Height();
CDC memDC;
memDC.CreateCompatibleDC(&dc);
CBitmap memBitmap, *oldBitmap;
memBitmap.CreateCompatibleBitmap(&dc, iWidth, iHeight);
oldBitmap = memDC.SelectObject(&memBitmap);
memDC.BitBlt(0,0,iWidth, iHeight, &dc, 0,0,SRCCOPY);
BITMAP bmp;
memBitmap.GetBitmap(&bmp);
FILE *fp = fopen("test2.bmp", "wb");
BITMAPINFOHEADER bih;
memset(&bih, 0, sizeof(bih));
bih.biBitCount = bmp.bmBitsPixel;
bih.biCompression = BI_RGB;//表示不压缩
bih.biHeight = bmp.bmHeight;
bih.biPlanes = 1;//位平面数,必须为1
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;
bih.biWidth = bmp.bmWidth;
BITMAPFILEHEADER bfh;
memset(&bfh, 0, sizeof(bfh));
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;
bfh.bfType = (WORD)0x4d42;//必须表示"BM"
fwrite(&bfh, 1, sizeof(BITMAPFILEHEADER), fp);
fwrite(&bih, 1, sizeof(bih), fp);
byte * p = new byte[bmp.bmWidthBytes * bmp.bmHeight];
GetDIBits(memDC.m_hDC, (HBITMAP)memBitmap.m_hObject, 0, iHeight, p, (LPBITMAPINFO)&bih, DIB_RGB_COLORS);
fwrite(p, 1, bmp.bmWidthBytes * bmp.bmHeight, fp);
delete [] p;
fclose(fp);
memDC.SelectObject(oldBitmap);
}
效果:
全屏截取:
只截取对话框: