本文由CSDN使用者zuishikonghuan所作,轉載請注明出處 http://blog.csdn.net/zuishikonghuan/article/details/46547157 GetWindowRect/GetClientRect
擷取視窗矩形/擷取視窗客戶區矩形
函數原型為:
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;
}
}