我们在使用reader阅读文件时,在工具栏选项有一个手状的工具,点击后可实现我们对当前文本拖动,那么我们在vc中是如何实现的呢?原理是什么呢?
当我练习打字咯....
在求是科技的这本书<VC++实效编程百例>>里有一个贴切的例子:P78 实例32:拖放选中对象.
如下:
实现方法:当鼠标左键在图形区域被按下时,捕捉所有鼠标消息,并且响应鼠标移动消息,随时师尊图形的位置,重画图形.
(1)利用AppWizard创建SDI床的应用等距离 MoveSelOb,并且选择视图类的蕨类为CScrollView.
(2)在视图类的头文件中增加4个变量,用来保存图形位置和鼠标捕捉情况,其代码如下:
protected:
const CSize m_sizeEllipse;
CPoint m_pointLeft;
CSize m_sizeOffset;
BOOL m_bCaptured;
(3)在构造类的构造函数中初始化变量,其代码如下:
CMoveSelObView::CMoveSelObView():m_sizeEllipse(100,-100),m_pointLeft(0,0),m_sizeOffset(0,0)
{
// TODO: add construction code here
m_bCaptured= FALSE;
}
(4)在视图类的 OnInitialUpdate 函数中初始化视图的滚动范围:
void CMoveSelOb1View::OnInitialUpdate()
{
CView::OnInitialUpdate();
// TODO: Add your specialized code here and/or call the base class
// 设置滚动范围
CSize sizeTotal(800,1050); // 8-by-10.5 inches
CSize sizePage(sizeTotal.cx/2,sizeTotal.cy/2);
CSize sizeLine(sizeTotal.cx/50,sizeTotal.cy/50);
SetScrollSizes(MM_LOENGLISH, sizeTotal,sizePage,sizeLine);
}
(5)在视图类的 OnDraw 函数中绘图:
void CMoveSelOb1View::OnDraw(CDC* pDC)
{
CMoveSelOb1Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
// 创建红色画刷
CBrush brushHatch(HS_DIAGCROSS, RGB(255,0,0));
CPoint point(0,0);
// 转换逻辑坐标为设备坐标
pDC->LPtoDP(&point);
pDC->SetBrushOrg(point);
CBrush* pOldBrush = pDC->SelectObject(&brushHatch);
// 画红色圆圈
pDC->Ellipse(CRect(m_pointLeft,m_sizeEllipse));
pDC->SelectObject(pOldBrush);
}
(6)响应WM_LBUTTONDOWN 消息:
void CMoveSelOb1View::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CRect rectEllipse(m_pointLeft,m_sizeEllipse);
CRgn circle;
CClientDC dc(this);
OnPrepareDC(&dc);
dc.LPtoDP(rectEllipse);
circle.CreateEllipticRgnIndirect(rectEllipse);
if(circle.PtInRegion(point)){
// 捕捉鼠标
SetCapture();
m_bCaptured= TRUE;
CPoint pointLeft(m_pointLeft);
dc.LPtoDP(&pointLeft);
m_sizeOffset=point-pointLeft;
// 设置光标形状为十字状
::SetCursor(::LoadCursor(NULL, IDC_CROSS));
}
CView::OnLButtonDown(nFlags, point);
}
(7)响应 WM_LBUTTONUP :
void CMoveSelOb1View::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
if(m_bCaptured){
// 释放鼠标捕捉
::ReleaseCapture();
m_bCaptured= FALSE;
}
CView::OnLButtonUp(nFlags, point);
}
(8)响应 WM_MOUSEMOVE:
void CMoveSelOb1View::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
if(m_bCaptured){
// 如果有图形被选中,并且鼠标捕捉则更新图形位置
CClientDC dc(this);
OnPrepareDC(&dc);
CRect rectOld(m_pointLeft,m_sizeEllipse);
dc.LPtoDP(&rectOld);
// 擦除老位置的图形
InvalidateRect(rectOld,TRUE);
m_pointLeft = point - m_sizeOffset;
dc.DPtoLP(&m_pointLeft);
// 在新位置画图形
CRect rectNew(m_pointLeft,m_sizeEllipse);
dc.LPtoDP(rectNew);
InvalidateRect(rectNew, TRUE);
}
CView::OnMouseMove(nFlags, point);
}
//---------------- THE END --------------------
如果要VC工程的完整代码,请给我email. toahming@126.com,书没随送代码,只有自己敲。^_^