GetWindowRect和GetClientRect及ScreenToClient,ClientToScree的关系
转发自:https://www.cnblogs.com/chenchenluo/archive/2012/10/08/2715586.html
新建一个基于对话框的MFC的exe程序:
删除对话框的所有按钮,并添加一个test按钮,添加一个Static控件,ID为IDC_STATIC:

双击test按钮,在响应函数中添加以下代码:
1 void CTestMapDlg::OnBtnTest()
2 {
3 // TODO: Add your control notification handler code here
4 CRect rect;
5 CString str;
6
7 CWnd* pStatic = (CWnd*) GetDlgItem(IDC_STATIC);
8
9 pStatic->GetWindowRect(&rect);
10 str.Format("In GetWindowRect: rect.left = %d, rect.top = %d, rect.right = %d, rect.bottom = %d",
11 rect.left, rect.top, rect.right, rect.bottom);
12 MessageBox(str);
13
14 pStatic->ScreenToClient(&rect);
15 str.Format("In GetWindowRect and after ScreenToClient: rect.left = %d, rect.top = %d, rect.right = %d, rect.bottom = %d",
16 rect.left, rect.top, rect.right, rect.bottom);
17 MessageBox(str);
18
19 pStatic->GetClientRect(&rect);
20 str.Format("In GetClientRect: rect.left = %d, rect.top = %d, rect.right = %d, rect.bottom = %d",
21 rect.left, rect.top, rect.right, rect.bottom); MessageBox(str);
22
23 pStatic->ClientToScreen(&rect);
24 str.Format("In GetClientRect and after ClientToScreen: rect.left = %d, rect.top = %d, rect.right = %d, rect.bottom = %d",
25 rect.left, rect.top, rect.right, rect.bottom);
26 MessageBox(str);
27 }


这个显示的是以屏幕左上角为原点的像素坐标。
说明GetWindowRect(&rect) 得到的矩形坐标是以屏幕左上角的点为原点的坐标。

这个显示的是以TestMap对话框的静态控件左上角为起点的像素坐标。
说明ScreenToClient(&rect) 能把以屏幕左上角的坐标转换成以调用该函数对象所关联的窗口(静态控件)的左上角的坐标。

这个显示的是以TestMap对话框的静态控件左上角为起点的像素坐标。
说明GetClientRect(&rect) 得到的坐标等于以
GetWindowRect(&rect)和 ScreenToClient(&rect) 的组合。
PS:仅对于那些没有边框的静态控件。

这个显示的是以屏幕左上角为原点的像素坐标。
说明GetWindowRect(&rect) 等于
GetClientRect(&rect) 和 ScreenToWindow(&rect) 的组合。


浙公网安备 33010602011771号