如何让CRectTracker的m_rect不超出一定的范围,比如screen或者某个document的范围

时间:2023-12-30 19:38:02

最近在尝试做一个QQ截图那样的工具,其中一个功能就是要做一个选择框,自然用到了CRectTracker

但是有一个很关键的东西就是,拖拽CRectTracker的时候,不能让CRectTracker“移出”屏幕,否则截图出来就有黑色的块

怎么办?搜了一下,也没搜到什么有用的资料(可能是我搜索技能太low)

去MSDN看着CRectTracker的文档,想一想应该是Override其中某个method就可以的。

后来琢磨了一下,搞定了,直接Override CRectTracker::OnChangedRect即可,代码直接贴下面:

CVSCRectTracker.h

 #pragma once

 #include <afxext.h>

 // Canvas CRectTracker
class CVSCRectTracker :
public CRectTracker
{
public:
CVSCRectTracker(LPCRECT lpSrcRect, UINT nStyle);
/******************************************************
In order to restrict the tracker's rectangle within
the range of the screen. Override this method, when the rectangle's
device coordinates are beyond the range of
the device (the screen), refuse to make the change.
******************************************************/
virtual void OnChangedRect(const CRect& rectOld);
};

CVSCRectTracker.cpp

 #include "CVSCRectTracker.h"

 CVSCRectTracker::CVSCRectTracker(LPCRECT lpSrcRect, UINT nStyle) : CRectTracker(lpSrcRect, nStyle)
{
} void CVSCRectTracker::OnChangedRect(const CRect& rectOld)
{
// get screen metrics
LONG cxScreen(::GetSystemMetrics(SM_CXSCREEN)), cyScreen(::GetSystemMetrics(SM_CYSCREEN));
// If coordinates are out of the screen, reset the rectangle to its last position
if (m_rect.left <= || m_rect.right >= cxScreen)
m_rect.left = m_rectLast.left, m_rect.right = m_rectLast.right;
if (m_rect.top <= || m_rect.bottom >= cyScreen)
m_rect.top = m_rectLast.top, m_rect.bottom = m_rectLast.bottom;
CRectTracker::OnChangedRect(m_rect);
}

Canvas.cpp

CRectTracker *tracker = new CVSCRectTracker(&rect, CRectTracker::resizeOutside | CRectTracker::dottedLine);

然后你该怎么用怎么用就可以了