由于一个小项目的需要,必须做控件的拖曳。以前还真没有想过这种问题。先来看看有没有处理消息,比如drag什么的,很遗憾没有。再来看看有没有函数,好像也没有,郁闷。没办法了。只好用绝招,自己做一个派生类把,下面我就以编辑框为例,简单说明一下拖曳的过程。 1。从CEdit派生一个类为CmyEdit。 2。添加左键处理函数: void Cmyedit::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default pp=point; // pp是Cmyedit的成员变量 SetTimer(5,10,NULL); // 引发定时器 CEdit::OnLButtonDown(nFlags, point);} void Cmyedit::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default KillTimer(5); // 关闭定时器 CEdit::OnLButtonUp(nFlags, point);} 3。添加定时消息处理: void Cmyedit::OnTimer(UINT nIDEvent) { // TODO: Add your message handler code here and/or call default if(nIDEvent==5){ //获得鼠标当前位置,转换为父窗口内的坐标 CPoint cursor_Pos; GetCursorPos(&cursor_Pos); GetParent()->ScreenToClient(&cursor_Pos); //鼠标原来单击位置pp,转换为所在父窗口内的坐标 CPoint edit_Pos=pp; ClientToScreen(&edit_Pos); GetParent()->ScreenToClient(&edit_Pos); // 获得控件的大小,并且转换到父窗口的坐标,主要是为了获得左上角的坐标,方便下面的movewindow调用 CRect edit_rect; GetWindowRect(edit_rect); GetParent()->ScreenToClient(&edit_rect); // 利用向量相等的性质求得鼠标移动后的新左上角坐标 int x=edit_rect.left+(cursor_Pos.x-edit_Pos.x); int y=edit_rect.top+(cursor_Pos.y-edit_Pos.y); MoveWindow(x,y,edit_rect.Width(),edit_rect.Height()); }CEdit::OnTimer(nIDEvent); } 4.改变鼠标形状 BOOL Cmyedit::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // TODO: Add your message handler code here and/or call default SetCursor(AfxGetApp()->LoadStandardCursor(IDC_SIZEALL)); return TRUE;} 这样就结束了。可以到处用了。符合拖动的要求了。

评论