函數說明
GetWindowRect
此函數是獲取窗體或者控件在屏幕坐標係下的坐標。
若此函數用於窗體初始化函數中,原點位於窗體的左上角;
若此函數在窗體初始化完成之後使用,原點位於屏幕的左上角。
ScreenToClient
此函數是將屏幕坐標轉化為客戶區坐標。
GetClientRect
此函數是獲取窗體或者控件客戶區的大小,一般來說,針對窗體還是控件,其獲取的Left、Top參數均為0;
ClientToScreen
此函數是將客戶區坐標轉化為屏幕坐標
MoveWindow
針對窗體,使用屏幕坐標;
針對控件,使用窗體客戶區坐標。
針對窗體進行測試 CRect rectClientRect;GetClientRect(rectClientRect); //top=0 botton=397 left=0 right=564CRect rectClientToScreen;rectClientToScreen = rectClientRect;ClientToScreen(rectClientToScreen); //top=26 botton=423 left=3 right=567CRect rectWinRect;GetWindowRect(rectWinRect); //top=0 botton=426 left=0 right=570CRect rectScreenToClient;rectScreenToClient = rectWinRect;ScreenToClient(rectScreenToClient); //top=-26 botton=400 left=-3 right=567int nTitltHeight = GetSystemMetrics(SM_CYCAPTION); //標題欄高度23MoveWindow(rectWinRect.left,rectWinRect.top,rectWinRect.Width(),rectWinRect.Height());//窗體不動
通過測試結果也可以證明,該對話框上下邊框相等,均為3。
其中左右邊框也為3。
在移動控件位置時注意事項
若針對控件使用GetWindowRect,則獲取的是控件的客戶區的大小。
若要獲取控件位於客戶區的坐標,則應該使用GetWindowRect,再使用ScreenToClient。
CRect rectButtonWinRect;GetDlgItem(IDC_BUTTON1)->GetClientRect(rectButtonWinRect);//top=0 botton=67 left=0 right=161CRect rectButtonClientRect;GetDlgItem(IDC_BUTTON1)->GetWindowRect(rectButtonClientRect);//top=49 botton=116 left=44 right=205ScreenToClient(rectButtonClientRect);GetDlgItem(IDC_BUTTON1)->MoveWindow(rectButtonClientRect);//控件處於原位置不動
List Control控件測試 CRect rectListWinRect;GetDlgItem(IDC_LIST1)->GetWindowRect(rectListWinRect); //top=159 botton=409 left=47 right=241CRect rectListClientRect;GetDlgItem(IDC_LIST1)->GetClientRect(rectListClientRect); //top=0 botton=246 left=0 right=190
其中
rectListWinRect.bottom-rectListWinRect.top != rectListClientRect.bottom - rectListClientRect.top;
這是由於List Control是具有邊框的。
GetWindowRect獲取的是整個控件相對於原點的位置;
GetClientRect獲取的是控件客戶區的位置。
彈窗測試1(GetWindowRect)
在Test窗體上點擊Button1,彈出Dialog窗體。
在Dialog的初始化窗體中執行如下代碼
CRect rectButtonWin;GetDlgItem(IDC_BUTTON2)->GetWindowRect(rectButtonWin);//top=431 botton=493 left=740 right=887
很顯然,得到的區域並不是以Dialog窗體左上角為坐標原點。
這是由於父窗體已經存在,此時的GetWindowRect是以屏幕左上角點為坐標原點。
彈窗測試2(MoveWindow)
點擊“彈窗”按鈕,彈出Dialog1對話框。
void CTestDlg::OnBnClickedButton1(){// TODO: 在此添加控件通知處理程序代碼CDlg1* dlg1 = new CDlg1();dlg1->Create(IDD_DIALOG1,this);CRect rec1;dlg1->GetWindowRect(rec1);dlg1->MoveWindow(40,50,rec1.Width(),rec1.Height());dlg1->ShowWindow(SW_SHOW);}若對話框屬性設置為Child,MoveWindow的坐標參數為Test窗體的客戶區坐標。若對話框屬性設置為Pop, MoveWindow的坐標參數為屏幕坐標。
參考博客