您的位置:首页 > 其它

CImage实现的全屏PNG截图

2016-02-03 13:39 387 查看
本来关于屏幕截图已经写了2篇博文了,但是效果都不是很理想,于是有了这个,直接使用CImage,代码简洁明了,比这个稳定:/article/10914852.html

最后截图生成的PNG文件保存在C:\ScreenShot文件夹下。

#include <atlimage.h>
#include <atltime.h>

//截取全屏保存为png
CString ScreenShot()
{
HDC hDCScreen = ::GetDC(NULL);//首先获取到屏幕的句柄
int nBitPerPixel = GetDeviceCaps(hDCScreen, BITSPIXEL);//获取到每个像素的bit数目
int nWidthScreen = GetDeviceCaps(hDCScreen, HORZRES);
int nHeightScreen = GetDeviceCaps(hDCScreen, VERTRES);
//创建一个CImage的对象
CImage m_MyImage;
//Create实例化CImage,使得其内部的画布大小与屏幕一致
m_MyImage.Create(nWidthScreen, nHeightScreen, nBitPerPixel);
//获取到CImage的 HDC,但是需要手动ReleaseDC操作,下面是MSDN的说明
//Because only one bitmap can be selected into a device context at a time,
//you must call ReleaseDC for each call to GetDC.
HDC hDCImg = m_MyImage.GetDC();
//使用bitblt 将屏幕的DC画布上的内容 拷贝到CImage上
BitBlt(hDCImg, 0, 0, nWidthScreen, nHeightScreen, hDCScreen, 0, 0, SRCCOPY);

//保存到的文件名
CString strFileName("C:\\");
strFileName += _T("ScreenShot\\");
CreateDirectory((LPCTSTR)strFileName,NULL);
CTime t = CTime::GetCurrentTime();
CString tt = t.Format(_T("%Y-%m-%d_%H-%M-%S"));
strFileName += tt;
strFileName += _T(".PNG");

//直接保存吧
m_MyImage.Save(strFileName,Gdiplus::ImageFormatPNG);

//前面调用了GetDC所以需要调用ReleaseDC释放掉
//详情请参见MSDN
m_MyImage.ReleaseDC();
return strFileName;
}

void main()
{
ScreenShot();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: