从Window Rect计算客户端大小和位置

时间:2018-04-05 13:23:10

标签: c++ winapi

如何使用window rect获取客户端大小和位置?这可能吗?

3 个答案:

答案 0 :(得分:1)

不确定您到底想要找到什么。也许尝试这样的事情:

#include <iostream>
#include <windows.h>

int main()
{
    RECT r;
    HWND h = GetConsoleWindow(); // or whatever window needed

    GetWindowRect(h, &r);
    std::cout << "Relative Client X,Y: " << r.left << "," << r.top << std::endl;
    std::cout << "Relative Client W,H: " << r.right - r.left << "," << r.bottom - r.top << std::endl;

    GetClientRect(h, &r);
    std::cout << "Client X,Y: " << r.left << "," << r.top << std::endl;
    std::cout << "Client W,H: " << r.right - r.left << "," << r.bottom - r.top << std::endl;
}

例如:

Relative Client X,Y: 100,100
Relative Client W,H: 947,594
Client X,Y: 0,0
Client W,H: 910,552

和/或如果您想获得相对于屏幕的客户区位置,您可以使用ClientToScreen功能。例如:

#include <windows.h>

int main()
{
    HWND h = GetConsoleWindow(); // or provided HWND
    POINT p{}; // defaulted to 0,0 which is always left and top of client area

    ClientToScreen(h, &p);
    SetCursorPos(p.x, p.y); // places cursor to the 0,0 of the client
}

答案 1 :(得分:0)

如果你有一个窗口RECT,左上角是窗口位置,你也可以使用窗口的左上角和右下角计算尺寸。

https://msdn.microsoft.com/en-us/library/windows/desktop/ms633519(v=vs.85).aspx

答案 2 :(得分:0)

我找到了解决方案:

RECT GetClientRectFromWindowRect(HWND hWnd, RECT rect)
{
    RECT v = { 0 };
    AdjustWindowRectEx(&v, 
        GetWindowLong(hWnd, GWL_STYLE), 
        !!GetMenu(hWnd), 
        GetWindowLong(hWnd, GWL_EXSTYLE)
        );
    RECT ret = { 0 };
    ret.bottom = rect.bottom - v.bottom;
    ret.left = rect.left - v.left;
    ret.right = rect.right - v.right;
    ret.top = rect.top - v.top;
    return ret;
}