获取窗口矩形/获取窗口客户区矩形
函数原型为:
BOOL WINAPI GetWindowRect(
_In_ HWND hWnd,
_Out_ LPRECT lpRect
);
BOOL WINAPI GetClientRect(
_In_ HWND hWnd,
_Out_ LPRECT lpRect
);
MSDN
https://msdn.microsoft.com/en-us/library/windows/desktop/ms633519(v=vs.85).aspx
https://msdn.microsoft.com/library/windows/desktop/ms633503(v=vs.85).aspx
hWnd:窗口句柄
lpRect:一个矩形结构的指针,用于输出矩形
返回值:非0成功,0失败。
RECT 矩形结构,原型为:
MSDN: https://msdn.microsoft.com/en-us/library/dd162897(v=vs.85).aspx
left
The x-coordinate of the upper-left corner of the rectangle.
top
The y-coordinate of the upper-left corner of the rectangle.
right
The x-coordinate of the lower-right corner of the rectangle.
bottom
The y-coordinate of the lower-right corner of the rectangle.
分别表示该矩形的左侧/顶部/右侧/底部坐标
其实我刚开始接触这两个API时,也挺迷惑,因为网上的资料不太好理解,有的还有错误,MSDN上说的也不是很详细,因此,我就自己测试一下,结果如下:
GetWindowRect:
如果窗口句柄是一个窗口,那么获得的是窗口(含边框)相对于屏幕左上角的坐标
如果窗口句柄是一个控件(子窗口),那么也是这个坐标,如果想获取控件相对于窗口的坐标,可以使用ScreenToClient函数
GetClientRect:
如果窗口句柄是一个窗口,那么获得的是窗口(含边框)的宽度和高度,left和top都位0,若想获取客户区相对于屏幕的位置,可以使用ClientToScreen函数
如果窗口句柄是一个控件(子窗口),那么和窗口相同
注:ScreenToClient/ClientToScreen
Screen(屏幕坐标) 到 Client(客户区坐标)的转换/ 客户区的坐标点信息转换为整个屏幕的坐标
第一个参数是窗口句柄,第二个参数是point结构的指针。
下面是我写的几个函数,相信看了这几个函数就好理解了:
1。获取窗口宽度/高度
DWORD GetWindowWidth(HWND hWnd)
{
RECT r;
if (GetWindowRect(hWnd, &r) != 0){
return (r.right - r.left);
}
else{
return 0;
}
}
DWORD GetWindowHeight(HWND hWnd)
{
RECT r;
if (GetWindowRect(hWnd, &r) != 0){
return (r.bottom - r.top);
}
else{
return 0;
}
}
2。获取客户区宽度/高度
DWORD GetClientWidth(HWND hWnd)
{
RECT r;
if (GetClientRect(hWnd, &r) != 0){
return (r.right - r.left);
}
else{
return 0;
}
}
DWORD GetClientHeight(HWND hWnd)
{
RECT r;
if (GetClientRect(hWnd, &r) != 0){
return (r.bottom - r.top);
}
else{
return 0;
}
}
3。获取窗口相对于屏幕的x坐标/y坐标
DWORD GetWindowLeft(HWND hWnd)
{
RECT r;
if (GetWindowRect(hWnd, &r) != 0){
return r.left;
}
else{
return 0;
}
}
DWORD GetWindowTop(HWND hWnd)
{
RECT r;
if (GetWindowRect(hWnd, &r) != 0){
return r.top;
}
else{
return 0;
}
}
4。获取控件相对于窗口客户区的x坐标/y坐标
DWORD GetChildLeft(HWND hWnd,HWND hp)
{
RECT r;
if (GetWindowRect(hWnd, &r) != 0){
ScreenToClient(hp,(LPPOINT)&r);
return r.left;
}
else{
return 0;
}
}
DWORD GetChildTop(HWND hWnd,HWND hp)
{
RECT r;
if (GetWindowRect(hWnd, &r) != 0){
ScreenToClient(hp, (LPPOINT)&r);
return r.top;
}
else{
return 0;
}
}