Search code examples
winapiscrollbaralignmentcreatewindow

CreateWindow Scrollbar alignment issue


Consider the following partial code. My problem is that the Scrollbar is not aligned with the rectangle. I get a rectangle and a scrollbar with a large gap between the two. I figured I could experiment and find out what the "offset" is and just put that in but I'd like to understand why the scrollbar apparently does not seem to honor the coordinates.

hCDC = GetDC(hCWnd);
bkgBrush = CreateSolidBrush( BGColor );
SetMapMode( hCDC, MM_TEXT );
SelectObject( hCDC, bkgBrush );
Rectangle(hCDC, VTRect->left, VTRect->top, VTRect->right, VTRect->bottom);

iHThumb = GetSystemMetrics(SM_CXHTHUMB);
iVThumb = GetSystemMetrics(SM_CYVTHUMB);

hInstance = NULL;

if( hWndVertScroll )
DestroyWindow( hWndVertScroll );

hWndVertScroll = CreateWindow(
            "Scrollbar",
            (LPSTR)NULL,
            WS_CHILD | WS_VISIBLE | SBS_VERT | SBS_RIGHTALIGN,
            VTRect->left,VTRect->top,VTRect->right,VTRect->bottom-iVThumb ,
            hCWnd,
            NULL,
            hInstance,
            NULL);

To correct for the gap, I'd invoke the CreateWindow call using the following:

hWndVertScroll = CreateWindow(
            "Scrollbar",
            (LPSTR)NULL,
            WS_CHILD | WS_VISIBLE | SBS_VERT | SBS_RIGHTALIGN,
            VTRect->left,VTRect->top,VTRect->right - 100 ,VTRect->bottom-iVThumb ,
            hCWnd,
            NULL,
            hInstance,
            NULL);

but I don't understand why VTRect->right - 100 is required to but the scroll bar up against the right side of the Rectangle. Note that I did try VTRect->right - iHThumb but I still have a gap albeit a smaller one.

Screen shot of the red rectangle and scrollbar and the gap between the two:

alt text


Solution

  • VTRect->left,VTRect->top,VTRect->right - 100 ,VTRect->bottom-iVThumb

    The arguments you pass to CreateWindow() with these values are x, y, nWidth and nHeight. Width and height, not right and bottom. Fix:

    VTRect->left, VTRect->top, VTRect->right - VTRect->left, VTRect->bottom - VTRect->top