How to set button control's position to be exactly in the middle of the window in Win32 API

Viewed 388

I am currently a noob for Win32 API and learning it. I want to learn how can we set the position of a button control to be exactly in the middle of the main window.

I am just creating a simple button like this in the WM_CREATE message of the WndProc function :-

HWND hBtn;

hBtn = CreateWindow
(
    L"Button", L"Hello",
    WS_VISIBLE | WS_CHILD,
    0, 0, 125, 50,
    hWnd, NULL, NULL, NULL
);

Note that hBtn is globally defined.

I am just subclassing the button control to get the hand cursor while hovering it. Its pretty simple.

SetWindowSubclass (hBtn, ButtonSubclass, NULL, NULL);

At last I just want the button to be exactly in the middle of the screen when the window is resized.

2 Answers

You need to set the left and top position of the button as the size of the parent window divided by two minus the size of the button divided by two. And then repaint and recalculate every time the window is resized.

You only need to recalculate the position of the button in the WM_SIZE of the parent window to center it:

case WM_CREATE:
    hBtn = CreateWindow
    (
        L"Button", L"Hello",
        WS_VISIBLE | WS_CHILD,
        0, 0, 125, 50,
        hWnd, NULL, NULL, NULL
    );
    break;
case WM_SIZE:
{
    UINT width = LOWORD(lParam);
    UINT height = HIWORD(lParam);
    RECT rc = {};
    GetClientRect(hBtn,&rc);
    int x = (int)(width - (rc.right - rc.left)) / 2;
    int y = (int)(height - (rc.bottom - rc.top)) / 2;
    MoveWindow(hBtn, x, y, rc.right - rc.left, rc.bottom - rc.top, 1);
}
break;
Related