2012-09-11 83 views
1

我有一個對話框在MFC C++中有一個CButton附加。 我想修改OnSize(),以便按鈕將錨定到左下角。C++ MFC按鈕消失在窗口調整大小

if (btn.m_hWnd) { 
     CRect winRect; 
     GetWindowRect(&winRect); 

     int width = winRect.right - winRect.left; 
     int height = winRect.bottom - winRect.top; 

     int x = width - wndWidth; 
     int y = height - wndHeight; 


     CRect rect; 
     btn.GetWindowRect(&rect); 
     rect.left += x; 
     rect.top += y; 
     btn.MoveWindow(&rect); 
     ScreenToClient(&rect); 
     btn.ShowWindow(SW_SHOW); 
    } 

x和y是窗口變化多少的差異,並將被添加到按鈕的起始座標。

我不知道最後2個命令(我可能會刪除它們),但後來我運行該程序的按鈕消失。

我需要知道一種方法來移動按鈕x和y。

回答

2

原始代碼對於父對話框和按鈕都使用了錯誤的座標系。

停靠在左下方會是這樣一個正確的方法:

if (btn.m_hWnd) { 
    CRect winRect; 
    GetClientRect(&winRect); 

    CRect rect; 
    btn.GetWindowRect(&rect); 
    ScreenToClient(&rect); 

    int btnWidth = rect.Width(); 
    int btnHeight = rect.Width(); 
    rect.left = winRect.right-btnWidth; 
    rect.top = winRect.bottom-btnHeight; 
    rect.right = winRect.right; 
    rect.bottom = winRect.bottom; 
    btn.MoveWindow(&rect); 
} 

OR

if (btn.m_hWnd) { 
    CRect winRect; 
    GetClientRect(&winRect); 

    CRect rect; 
    btn.GetWindowRect(&rect); 
    ScreenToClient(&rect); 

    int btnWidth = rect.Width(); 
    int btnHeight = rect.Width(); 
    btn.SetWindowPos(NULL,winRect.right-btnWidth,winRect.bottom-btnHeight,0,0,SWP_NOSIZE|SWP_NOZORDER); 
} 
1

基本上,答案應該是在MoveWindow之前做ScreenToClient!你需要熟悉什麼函數返回或使用客戶端座標(以及相對於這些客戶端座標是什麼)以及哪些屏幕座標;這是MFC的一部分,可能會讓人感到困惑。至於你的問題:

CWnd::GetWindowRect返回屏幕座標; CWnd::MoveWindow預計相對於父CWnd的座標(或者如果它是頂級窗口則顯示在屏幕上)。因此,在調用MoveWindow之前,必須將由GetWindowRect返回的rect轉換爲父窗口的客戶端座標;假設pParent是CWnd *btn父窗口,那麼你的移動代碼應該是這樣的:

CRect rect; 
btn.GetWindowRect(&rect); 
pParent->ScreenToClient(&rect); // this line and it's position is important 
rect.left += x; 
rect.top += y; 
btn.MoveWindow(&rect); 

如果你在父窗口的方法(因爲我認爲你是,既然你提到篩上部分的對話框),然後只是省略pParent->。您現在執行ScreenToClient的方式,它對MoveWindow沒有影響,因爲它在它之後執行!