已经小小封装了一下,在LbuttonDown里调用 Track 即可。代码一半是抄了别人的,一半是研究了CRectTracker的源码,最下面已提供工程源码下载地址.
下面是 CCtrlTracker.h
class CCtrlTracker
{
public:
void Track(CWnd * pWnd,CPoint ptPoint);
CCtrlTracker();
virtual ~CCtrlTracker();
private:
CPoint m_ptOld;
CWnd * m_pWnd;
protected:
void MoveWindowEx();
};
下面就是CCtrlTracker.
void CCtrlTracker::Track(CWnd * pWnd,CPoint ptPoint)
{
m_ptOld = ptPoint;
m_pWnd = pWnd;
pWnd->SetCapture();
for (;;)
{
MSG msg;
VERIFY(::GetMessage(&msg, NULL, 0, 0));
if (CWnd::GetCapture() != pWnd)
break;
switch (msg.message)
{
// handle movement/accept messages
case WM_LBUTTONUP:
ReleaseCapture();
break;
case WM_MOUSEMOVE:
MoveWindowEx();
break;
// handle cancel messages
case WM_KEYDOWN:
if (msg.wParam != VK_ESCAPE)
break;
case WM_RBUTTONDOWN:
// just dispatch rest of the messages
default:
DispatchMessage(&msg);
break;
}
}
}
void CCtrlTracker::MoveWindowEx()
{
CPoint cursor_Pos;
GetCursorPos(&cursor_Pos);//该函数检取光标的位置,以屏幕坐标表示。
m_pWnd->GetParent()->ScreenToClient(&cursor_Pos); //该函数把屏幕上指定点的屏幕坐标转换成用户坐标。
CPoint edit_Pos= m_ptOld;
m_pWnd->ClientToScreen(&edit_Pos);//该函数将指定点的用户坐标转换成屏幕坐标
m_pWnd->GetParent()->ScreenToClient(&edit_Pos);
// 获得控件的大小,并且转换到父窗口的坐标,主要是为了获得左上角的坐标,方便下面的movewindow调用
CRect edit_rect;
m_pWnd->GetWindowRect(edit_rect);//该函数返回指定窗口的边框矩形的尺寸。该尺寸以相对于屏幕坐标左上角的屏幕坐标给出。
m_pWnd->GetParent()->ScreenToClient(&edit_rect);
CRect parentRect;
m_pWnd->GetParent()->GetClientRect(parentRect);
// 利用向量相等的性质求得鼠标移动后的新左上角坐标
int x=edit_rect.left+(cursor_Pos.x-edit_Pos.x);
int y=edit_rect.top+(cursor_Pos.y-edit_Pos.y);
if (x<0)
{
x=0;
}
if (y<0)
{
y=0;
}
if (x+edit_rect.Width()>parentRect.Width())
{
x = parentRect.Width() - edit_rect.Width();
}
if (y+edit_rect.Height()>parentRect.Height())
{
y = parentRect.Height() - edit_rect.Height();
}
m_pWnd->MoveWindow(x,y,edit_rect.Width(),edit_rect.Height());
m_pWnd->Invalidate();
}
源代码下载地址