前面讲了屏幕截图的一点知识,其实是很好懂的。如果我想要截取屏幕的部分区域怎么办呢?
下面就来讲一下。
要保证截图的时候所有窗口都是无效的,这样在鼠标滑动的时候才不容易丢失焦点。可是
这样办得到吗?至少我现在认为是不可能的,也许真的有某种方式可以做到。既然这样想行
不通,那就换一个思路吧。我们可以采用欺骗的手段,先新建一个对话框,然后让它充满整
个屏幕并且始终保持在所有窗口的最前面,然后将整个屏幕截取出来使之画满整个对话框窗
口,然后记录鼠标在此图像内的截图区域,再传递给主窗口就可以了。这是我在网上找到的
一个比较容易懂的方法。
具体实现如下:
(1)新建一个对话框,设置属性为无标题,无边框,新建类CCutScreenAreaDlg,在初始化函数
中将其设置为所有窗口最前。
int cxScreen,cyScreen;
cxScreen=GetSystemMetrics(SM_CXSCREEN);
cyScreen=GetSystemMetrics(SM_CYSCREEN);
SetWindowPos(&wndTopMost,0,0,cxScreen,cyScreen,SWP_SHOWWINDOW);
(2)然后重载其WM_ERASEBKGND消息。
BOOL CCutScreenAreaDlg::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
CDC *pDesktopDC=GetDesktopWindow()->GetDC();
CDC memDC;
memDC.CreateCompatibleDC(pDesktopDC);
CRect RectDesktop;
GetDesktopWindow()->GetClientRect(&RectDesktop);
CBitmap bmpdesktop;
bmpdesktop.CreateCompatibleBitmap(pDesktopDC,RectDesktop.Width(),RectDesktop.Height());
CRect rect;
GetClientRect(&rect);
pDC->StretchBlt(0,0,rect.Width(),rect.Height(),pDesktopDC,0,0,RectDesktop.Width(),RectDesktop.Height(),SRCCOPY);
return TRUE;
}
(3)记录鼠标选中的区域,即左键按下为起点,右键按下为中点。
void CCutScreenAreaDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
StartPoint = point;
CDialog::OnLButtonDown(nFlags, point);
}
void CCutScreenAreaDlg::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
EndPoint = point;
CDialog::OnLButtonUp(nFlags, point);
}
(4)在父窗口内截取图像,用到函数CutScreenArea(CRect Rect)。
void CMyView::CutScreenArea(CRect Rect)
{
CDC *pDC=GetDC();
CRect rc;
CBrush brush;
brush.CreateSolidBrush(RGB(255,255,255));
GetClientRect(&rc);
pDC->FillRect(&rc,&brush);
CDC *pDesktopDC=GetDesktopWindow()->GetDC();
CRect RectDesktop;
GetDesktopWindow()->GetClientRect(&RectDesktop);
CDC memDC;
memDC.CreateCompatibleDC(pDesktopDC);
CBitmap bmpdesktop;
bmpdesktop.CreateCompatibleBitmap(pDesktopDC,RectDesktop.Width(),RectDesktop.Height());
CRect rect;
GetClientRect(&rect);
pDC->StretchBlt(0,0,rect.Width(),rect.Height(),pDesktopDC,Rect.left,
Rect.top,Rect.Width(),Rect.Height(),SRCCOPY);
grect = Rect;
}
(5)添加一个按钮消息响应函数OnCutscreenarea() 。
void CMyView::OnCutscreenarea()
{
// TODO: Add your command handler code here
HCURSOR hCursor=AfxGetApp()->LoadCursor(IDC_CURSOR1);
SetCursor(hCursor);
CCutScreenAreaDlg dlg;
if(IDOK == dlg.DoModal())
{
StartPoint = dlg.StartPoint;
EndPoint = dlg.EndPoint;
CRect rect;
rect.left = StartPoint.x;
rect.right = EndPoint.x;
rect.bottom = EndPoint.y;
rect.top = StartPoint.y;
grect = rect;
CutScreenArea(grect);
}
}
经过以上步骤就能在客户区内显示截取的区域图像了。
下一次讲怎么保存图像。
转载地址:http://blog.163.com/lvan100@yeah/blog/static/68117214201072411188309/