How do I find position of a Win32 control/window relative to its parent window?

前端 未结 4 1864
失恋的感觉
失恋的感觉 2020-12-05 17:53

Given handle of a Win32 window, I need to find position of it relative to its parent window.

I know several functions (e.g.; GetWindowRect() and GetClientRect()), bu

4条回答
  •  爱一瞬间的悲伤
    2020-12-05 18:39

    I know it's been answered before, but it's much easier to just get a child window's rect in screen coordinates, get it's position (POINT ptCWPos = {rectCW.left, rectCW.top};) and use the ScreenToClient() function, that will transform the screen coordinate point to the window's client coordinate point:

    PS: I know that looks like a lot more code, but most of it is fiddling with the rect position; in most cases one will actually need the rect position rather than the whole rect.


    HWND hwndCW, hwndPW; // the child window hwnd
                         // and the parent window hwnd
    RECT rectCW;
    GetWindowRect(hwndCW, &rectCW); // child window rect in screen coordinates
    POINT ptCWPos = { rectCW.left, rectCW.top };
    ScreenToClient(hwndPW, &ptCWPos); // transforming the child window pos
                                      // from screen space to parent window space
    LONG iWidth, iHeight;
    iWidth = rectCW.right - rectCW.left;
    iHeight = rectCW.bottom - rectCW.top;
    
    rectCW.left = ptCWPos.x;
    rectCW.top = ptCWPos.y;
    rectCW.right = rectCW.left + iWidth;
    rectCW.bottom = rectCW.right + iHeight; // child window rect in parent window space
    
    

提交回复
热议问题