来源:http://blog.csdn.net/sanshao1314/article/details/8703350
抓屏的实现
最近研究了抓屏的功能,抓屏过后把图片保持成JPG图像格式,百度、Google了好一阵终于有点明白了,特此在这里写下来和大家一起分享。
微软规定程序员不能直接操作硬件,所以我们只能通过其他方式去实现,这里我理解的是硬件就是风景,我们总不能对风景直接操作吧,那我们只能把风景画下来,这样就变得可操作了,要作画我们就要准备好工具,比如纸、笔、墨等,这种行为在计算机里我们把它叫做一种设备环境,你要在计算机里作图,设备环境的概念很重要,这种设备环境在计算机里用DC表示,我们可以同过GetDC、GetWindowDC、CClientDC方法来获得设备环境,好了下面进入正题。
首先Windows最重要的一个概念就是窗口了,桌面也是一种窗口,既然桌面是以个窗口我们是不是就可以获得桌面的窗口句柄呢,当然可以的,我们可以通过GetDesktopWindow函数来获取桌面窗口的句柄,
函数原型:HWND GetDesktopWindow(VOID);
msdn:
The GetDesktopWindow function returns a handle to the desktop window. The desktop window covers the entire screen. The desktop window is the area on top of which all icons and other windows are painted.
Return Values
The return value is a handle to the desktop window.
函数原型:HDC GetDC(
HWND hWnd // handle to window
);
msdn:
The GetDC function retrieves a handle to a display device context (DC) for the client area of a specified window or for the entire screen. You can use the returned handle in subsequent GDI functions to draw in the DC.
Parameters
-
hWnd
- [in] Handle to the window whose DC is to be retrieved. If this value is NULL,GetDC retrieves the DC for the entire screen.
- int x = ::GetDeviceCaps(hdc,HORZRES);//获得桌面宽度
- int y = ::GetDeviceCaps(hdc,VERTRES);//获得桌面高度
- HDC hmemdc = ::CreateCompatibleDC(hdc);//创建一个画图环境这个环境和hdc相关联
- HBITMAP hBitMap = ::CreateCompatibleBitmap(hdc,x,y);//创建一个画图环境这个环境能够兼容位图这时候
- hBitMap就保持着当前桌面窗口的图像了,只不过这里的图片是位图形式的
- HBITMAP hold = (HBITMAP)::SelectObject(hmemdc,hBitMap);//把hBitMap对象选到hmemdc中
- BitBlt(hmemdc,0,0,x,y,hdc,0,0,SRCCOPY);//以复制的方式把hdc的设备环境区域COPY到hmemdc区域上
- SelectObject(hmemdc,hold);//把画笔选择回之前的画笔
- Bitmap bit(width, height), bit2(hbmp, NULL);
- Graphics g(&bit);
- g.ScaleTransform((float)width/x, (float)height/y);
- g.DrawImage(&bit2, 0, 0);
- Bitmap bit(x, y), bit2(hbmp, NULL);
- Graphics g(&bit);
- g.ScaleTransform((float)width/x, (float)height/y);
- g.DrawImage(&bit2, 0, 0);
- CLSID encoderClsid;
- GetEncoderClsid(L"image/jpeg", &encoderClsid);
- CString pszFileName = "D<span style="font-size:18px;">:</span>\\Temp.jpg";
- BSTR strWFileName = pszFileName.AllocSysString();
- bit.Save(strWFileName, &encoderClsid, NULL);
- ::SysFreeString(strWFileName);
- ::DeleteObject(hbmp);
- ::DeleteObject(hmemdc);
http://download.csdn.net/detail/sanshao1314/5168073
就写到这里了,欢迎和各位共同分享,如果你们还有什么好的想法和如何更好的去理解他,可以说出来大家一起分享分享,