MFC限制子窗口只在父窗口內移動

1,響應WM_MOVE消息 在裏面判斷就完了

進消息嚮導找到它然後雙擊吧,然後添加你自己的限制代碼(獲取父窗口的clientRect,就是限制區域)

取得父窗口的頂點和右下角座標,利用子窗口的頂點座標和右下角座標進行範圍的判斷即可
例如父窗口A(50.50)(100.100)子窗口的頂點座標應該大於等於X1>=50&&Y1>=50
右下角座標X2<=100&&Y2<=100

2,應該是WM_MOVING消息中進行處理,

3,如果子窗體非模態可以這樣:

if(NULL==m_dlg)
{
CRect rect;
GetClientRect(&rect);   //獲得客戶區的大小
m_dlg=new CDlg(this);                         

m_dlg-> Create(IDD_REMOTE,NULL); 
m_dlg-> ModifyStyle(0,WS_CHILD|WS_MINIMIZEBOX ); 
m_dlg-> SetWindowPos(NULL,0,30,rect.Width(),rect.Height(),SWP_NOMOVE | SWP_NOZORDER); 
m_dlg-> SetWindowPos(this,0,30,0,0, SWP_NOZORDER | SWP_NOSIZE); 
m_dlg ->SetParent(this); 
m_dlg-> ShowWindow(SW_SHOW);
}

4,SetWindowPlacement

5,/******************************************************************
* 函數名稱: OnMoving(UINT nSide, LPRECT lpRect)
* 函數描述: 限制子窗口的移動範圍
********************************************************************/
void CChildFrame::OnMoving( UINT nSide, LPRECT lpRect )
{
CRect rectParent;
GetParent()->GetClientRect(&rectParent);
GetParent()->ClientToScreen(&rectParent);
CRect rectChild;
GetWindowRect(&rectChild);

    lpRect->left = min(lpRect->left, rectParent.right - rectChild.Width());
    lpRect->left = max(lpRect->left, rectParent.left);

    lpRect->top  = min(lpRect->top, rectParent.bottom - rectChild.Height());
    lpRect->top  = max(lpRect->top, rectParent.top);

    lpRect->right = min(lpRect->right, rectParent.right);
    lpRect->right = max(lpRect->right, rectParent.left + rectChild.Width());
    
    lpRect->bottom = min(lpRect->bottom, rectParent.bottom);
    lpRect->bottom = max(lpRect->bottom, rectParent.top + rectChild.Height()); 

CMDIChildWnd::OnMoving(nSide, lpRect);
}
//////////////
這個是響應子窗口的WM_MOVING消息
在子窗口的WM_MOVE消息響應函數中也可以


6,不論是WM_SIZING或WM_MOVING,它們的lParam參數都是一個指向RECT結構的
對象的指針,該對象中裝有窗口改變尺寸或位置後的左上角和右下角座標。注意
此時窗口實際上還沒有改變到這個位置,所以可以通過改變這個RECT結構的對象
的成員值來限制窗口尺寸和位置的變化方向。
    在mfc裏,就是在OnSizing和OnMoving函數裏來做這個工作。這兩個函數的p
Rect參數就是消息裏的(RECT*)lParam。

void CMainFrame::OnSizing(UINT fwSide, LPRECT pRect) 
{
    CFrameWnd::OnSizing(fwSide, pRect);

    //限制窗口只能改變右邊的尺寸
    RECT rect;
    GetWindowRect(&rect);
    pRect->left=rect.left;
    pRect->bottom=rect.bottom;
    pRect->top=rect.top;
}

void CMainFrame::OnMoving(UINT fwSide, LPRECT pRect) 
{
    CFrameWnd::OnMoving(fwSide, pRect);

    //限制窗口只能上下移動
    RECT rect;
    GetWindowRect(&rect);
    pRect->left=rect.left;
    pRect->right=rect.right;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章