c++windowgdicreatewindow

Get exact window region size - CreateWindow window size isn't correct size of window


I've noticed something very annoying while trying to create a window in C++ and draw Rectangles that the window size doesn't match the size I set.

For example, If I set the 480x240 window and try to Draw rectangles from top to bottom, left to right by getting GetWindowRect(hwnd, &rect) and calculate the width and height:

rectangle_width = (rect.right - rect.left) / amountRectangleX;
rectangle_height = (rect.bottom - rect.top) / amountRectangleY;

if amountRectangleX = 2 and Y = 2 it draw 4 rectangles, but the width and height is "off" so it doesn't fill up the whole screen or it renders over it. The only way this can happen (I've done this in alot of other languages so I know it works) is that if I set Window Size = 480x240 I want that to be the area to "DRAW" on. Because if borders are included in the size of the window - that would be different on another computer with different Window Style and such. ANd I can't just "alter" this manually for my computer.

If I set window size = 480x240 and take a screenshot I see that the Window Space = 452x232 which is confusing. It would be OK if I set window size = 480x240 but when I GetWindowRect() I get 452x232 and not 480x240 which then is invalid because I have less space to draw on. This would explain why my Rectangles render beyond the window space and I do NOT want that. But I still want to be able to set my size = 480x240 or anything else but still have borders.

Why does it work this way and is there a solution to this problem? I can't be the only one that want to be able to set the resolution of a window and no matter what computer you use, that size you set IS the DRAW AREA that you can draw upon.


Solution

  • I use this method and now it works:

    if ( IsWindow( hwnd ) )
    {
    
    DWORD dwStyle = GetWindowLongPtr( hwnd, GWL_STYLE ) ;
    DWORD dwExStyle = GetWindowLongPtr( hwnd, GWL_EXSTYLE ) ;
    HMENU menu = GetMenu( hwnd ) ;
    
    RECT rc = { 0, 0, width, height } ;
    
    AdjustWindowRectEx( &rc, dwStyle, menu ? TRUE : FALSE, dwExStyle );
    
    SetWindowPos( hwnd, NULL, 0, 0, rc.right - rc.left, rc.bottom - rc.top, SWP_NOZORDER | SWP_NOMOVE ) ;
    
    }