拖动图片要响应3个鼠标消息
OnLButtonDown,OnLButtonUp,OnMouseMove
左键按下时:
要判断是否在图像内部按下的,若是捕获图片
左键释放时:
释放图片
鼠标移动时: 根据鼠标移动,实时重绘图片
为此,设三个类变量:
CPoint pt;// 保存图片起始坐标
BOOL bcapture; //图片是否捕获
//鼠标与图片起始点的偏移量,
//当鼠标按下去的点和图片的左上角的点 之间有个距离,
//这个距离在图片移动过程中是不变的,这个距离是不变,
//offsetsize=point-pt ,响应WM_MOVE的函数中,pt=point-offsetsize
CSize offsetsize; //鼠标与图片起始点的偏移量
int ImgWidth;
int ImgHeight;
CSize size;
首先是初始化:
Cshanchu1111View::Cshanchu1111View()
{
// TODO: 在此处添加构造代码
// TODO: add construction code here
bcapture=FALSE;
pt.x=0;
pt.y=0;
offsetsize.cx=0;
offsetsize.cy=0;
}
然后是响应OnLButtonDown消息
void Cshanchu1111View::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CRect selrc(pt,size);
CClientDC dc(this);
//OnPrepareDC(&dc);
CRgn rgn;
rgn.CreateRectRgnIndirect(&selrc);
if(rgn.PtInRegion(point))
{
//限制鼠标的移动区域
CRect rectView;
GetWindowRect(&rectView);
ClipCursor(&rectView);
SetCapture();
bcapture=TRUE;
CPoint rcpt(pt);
offsetsize=point-rcpt;
SetCursor(LoadCursor(NULL,IDC_CROSS));
}
CView::OnLButtonDown(nFlags, point);
}
响应UP消息
void Cshanchu1111View::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
ReleaseCapture();
bcapture=FALSE;
ClipCursor(NULL);
CView::OnLButtonUp(nFlags, point);
}
响应Move消息
void Cshanchu1111View::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
if(bcapture)
{
CClientDC dc(this);
//OnPrepareDC(&dc);
CRect oldrc(pt,size);
InvalidateRect(oldrc,TRUE);
pt=point-offsetsize;
CRect newrc(pt,size);
InvalidateRect(newrc,TRUE);
}
CView::OnMouseMove(nFlags, point);
}
onDraw函数
void Cshanchu1111View::OnDraw(CDC *pDC)
{
Cshanchu1111Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
CBitmap bitmap;
bitmap.LoadBitmap(IDB_BITMAP1);
BITMAP bitmapInfo;
bitmap.GetBitmap(&bitmapInfo);
size.cx=bitmapInfo.bmWidth;
size.cy=bitmapInfo.bmHeight;
CBitmap* pOldBimap;
CDC dcMem;
dcMem.CreateCompatibleDC(pDC);
pOldBimap=dcMem.SelectObject(&bitmap);
pDC->BitBlt(pt.x,pt.y,bitmapInfo.bmWidth,bitmapInfo.bmHeight,&dcMem,0,0,SRCCOPY);
dcMem.SelectObject(pOldBimap);
}