Windows平台C++截屏程序

CWnd *pDesktop = GetDesktopWindow();
CDC *pdeskdc = pDesktop->GetDC();
CRect re;
//获取桌面的大小  
pDesktop->GetClientRect(&re);
CBitmap bmp;//创建内存位图
bmp.CreateCompatibleBitmap(pdeskdc, re.Width(), re.Height());//建立位图和DC的联系
//创建一个兼容的内存画板  
CDC memorydc;
memorydc.CreateCompatibleDC(pdeskdc);
//选中画笔  
CBitmap *pold = memorydc.SelectObject(&bmp);
//绘制图像  
memorydc.BitBlt(0, 0, re.Width(), re.Height(), pdeskdc, 0, 0, SRCCOPY);
memorydc.SelectObject(pold);
BITMAP bit;
bmp.GetBitmap(&bit);
//定义 图像大小(单位:byte)  
DWORD size = bit.bmWidthBytes * bit.bmHeight;
//后面是创建一个bmp文件的必须文件头  
BITMAPINFOHEADER pbitinfo;
pbitinfo.biBitCount = 24;
pbitinfo.biClrImportant = 0;
pbitinfo.biCompression = BI_RGB;
pbitinfo.biHeight = bit.bmHeight;
pbitinfo.biPlanes = 1;
pbitinfo.biSize = sizeof(BITMAPINFOHEADER);
pbitinfo.biSizeImage = size;
pbitinfo.biWidth = bit.bmWidth;
pbitinfo.biXPelsPerMeter = 0;
pbitinfo.biYPelsPerMeter = 0;

Mat img(bit.bmHeight, re.Width(), CV_8UC3);
GetDIBits(pdeskdc->m_hDC, bmp, 0, bit.bmHeight, img.data, (BITMAPINFO*)
    &pbitinfo, DIB_RGB_COLORS);//将图像数据拷贝到内存中,这里用的opencv数据格式承接了图像数据以方便显示,可以根据需要改成其他的
imshow("", img);
waitKey(30);
img.release();

猜你喜欢

转载自blog.csdn.net/oHanTanYanYing/article/details/78687874