簡體   English   中英

如何將按鈕控件的 position 設置在 Win32 API 中 window 的中間

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

我目前是 Win32 API 和學習它的菜鳥。 我想了解如何將按鈕控件的 position 設置在主 window 的中間。

我只是在WndProc function 的WM_CREATE消息中創建一個像這樣的簡單按鈕:-

HWND hBtn;

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

請注意, hBtn是全局定義的。

我只是將按鈕控件子類化以在懸停時獲得手 cursor。 它很簡單。

SetWindowSubclass (hBtn, ButtonSubclass, NULL, NULL);

最后,當 window 調整大小時,我只希望按鈕正好位於屏幕中間。

您需要將按鈕的左側和頂部 position 設置為父 window 的大小除以 2 減去按鈕的大小除以 2。 然后每次調整 window 的大小時重新繪制和重新計算。

您只需要重新計算父 window 的WM_SIZE中按鈕的 position 即可使其居中:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM