MFC中左键移动窗口实现方法

来源:互联网 发布:淘宝图片轮播大小制作 编辑:程序博客网 时间:2024/05/22 01:32

一、

窗体的OnLButtonDown函数中加入如下代码:

  PostMessage(WM_NCLBUTTONDOWN,HTCAPTION,MAKELPARAM(point.x,   point.y));

SendMessage(WM_SYSCOMMAND,0xF012,0);  

 

 

二、一般思路

首先在对话框类中添加以下消息处理函数:  
  OnLButtonDown   左键按下  
  OnMouseMove       鼠标移动  
  OnLButtonUp       左键放开  
   
  然后在对话框类中添加两个变量用来表示是否移动窗口及按下鼠标后那个点(相对于窗口的)  
  BOOL   m_bIsMove;                 //是否处于移动状态  
  CPoint   m_CenterPt;           //移动点中心  
   
  再次初始化上面的变量,在对话框类的构造函数中:  
  m_bIsMove   =   FALSE;  
   
  最后处理三个消息函数如下:  
  void   CMoveWindowDemoDlg::OnLButtonDown(UINT   nFlags,   CPoint   point)    
  {  
  //   TODO:   Add   your   message   handler   code   here   and/or   call   default  
  m_bIsMove   =   TRUE;  
  m_CenterPt   =   point;  
   
  CDialog::OnLButtonDown(nFlags,   point);  
  }  
   
  void   CMoveWindowDemoDlg::OnMouseMove(UINT   nFlags,   CPoint   point)    
  {  
  //   TODO:   Add   your   message   handler   code   here   and/or   call   default  
  if   (m_bIsMove)  
  {  
  //获取移动偏移量  
  int   nX   =   point.x   -   m_CenterPt.x;  
  int   nY   =   point.y   -   m_CenterPt.y;  
   
  //正在处于移动状态  
  CRect   rect;  
  GetWindowRect(&rect);  
  rect.OffsetRect(nX,nY);  
  MoveWindow(rect);  
  }  
   
  CDialog::OnMouseMove(nFlags,   point);  
  }  
   
  void   CMoveWindowDemoDlg::OnLButtonUp(UINT   nFlags,   CPoint   point)    
  {  
  //   TODO:   Add   your   message   handler   code   here   and/or   call   default  
  m_bIsMove   =   FALSE;  
   
  CDialog::OnLButtonUp(nFlags,   point);  
  }  

简化:

  //   设对话框类变量   POINT   prePoint;  
   
  //   鼠标移动函数:  
   
  void   CDragMainWindowDlg::OnMouseMove(UINT   nFlags,   CPoint   point)    
  {  
  if(nFlags   ==   MK_LBUTTON)  
  {      
      RECT   rect;  
      GetWindowRect(&rect);  
      POINT   p   =   point;  
      ClientToScreen(&p);  
       
      MoveWindow(rect.left+p.x-prePoint.x,rect.top+p.y-prePoint.y,rect.right-rect.left,rect.bottom-rect.top);  
      prePoint   =   p;  
  }    
  CDialog::OnMouseMove(nFlags,   point);  
  }  
   
  //   配合   鼠标按下函数:  
   
  void   CDragMainWindowDlg::OnLButtonDown(UINT   nFlags,   CPoint   point)    
  {  
  RECT   rect;  
  GetWindowRect(&rect);  
  POINT   p   =   point;  
  ClientToScreen(&p);    
  prePoint   =   p;  
   
  CDialog::OnLButtonDown(nFlags,   point);  
  }  

原创粉丝点击