- 版本
VS2012
- 实例说明
实例完成一个屏幕截图软件
可以将屏幕的内容保持到位图文件内
- 关键技术
屏幕截图需要先建立一个屏幕的设备上下文,然后根据屏幕的设备上下文创建一个内存位图,最后将内存位图数据写入到文件就实现了屏幕截图操作,屏幕截图程序需要运行在系统托盘中,并且通过RegisterHotKey函数注册一个快截键,通过快截键进行截图操作。
- 设计过程
(1)新建基于对话框的应用程序。
(2)在对话框中添加按钮控件
(3)方法SaveScreen是接收到触发后的保存屏幕图像的实现。
- 源代码
void CFirstMFCDialog::OnBnClickedButtonscreenshot()
{
// TODO: 在此添加控件通知处理程序代码
CDC screendc;
screendc.CreateDC("DISPLAY", NULL, NULL, NULL);
CBitmap bmp;
int width = GetSystemMetrics(SM_CXSCREEN);
int height = GetSystemMetrics(SM_CYSCREEN);
bmp.CreateCompatibleBitmap(&screendc, width, height);
CDC memdc;
memdc.CreateCompatibleDC(&screendc);
CBitmap* old = memdc.SelectObject(&bmp);
memdc.BitBlt(0,0,width,height,&screendc,0,0,SRCCOPY);
memdc.SelectObject(old);
BITMAP bm;
bmp.GetBitmap(&bm);
DWORD size = bm.bmWidthBytes*bm.bmHeight;
LPSTR data = (LPSTR)GlobalAlloc(GPTR,size);
BITMAPINFOHEADER bih;
bih.biBitCount = bm.bmBitsPixel;
bih.biClrImportant = 0;
bih.biClrUsed = 0;
bih.biCompression = 0;
bih.biHeight = bm.bmHeight;
bih.biWidth = bm.bmWidth;
bih.biPlanes = 1;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biSizeImage = size;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
GetDIBits(screendc, bmp, 0, bih.biHeight, data, (BITMAPINFO*)&bih,DIB_RGB_COLORS);
CFile file;
BITMAPFILEHEADER hdr;
hdr.bfType = ((WORD)('M'<<8)|'B');
hdr.bfSize = 54 + size;
hdr.bfReserved1 = 0;
hdr.bfReserved2 = 0;
hdr.bfOffBits = 54;
if (file.Open("D:\\2\\test.bmp",CFile::modeCreate|CFile::modeWrite))
{
file.Write(&hdr, sizeof(BITMAPFILEHEADER));
file.Write(&bih, sizeof(BITMAPINFOHEADER));
file.Write(data, size);
file.Close();
}
GlobalFree(data);
Invalidate();
}
- 演示
