无法更改按钮的位置

Can't change position of button

本文关键字:位置 按钮      更新时间:2023-10-16

在C++应用程序中,我使用CreateWindowEx创建了一个按钮,然后尝试使用SetWindowPos更改其位置,但该按钮没有出现在我想要的位置。

有趣的是,当我调整窗口大小(使用鼠标,而不是以编程方式)时,我可以在一瞬间看到一个空白的轮廓,与按钮应该出现的按钮大小相同。这一定是因为我还调用 SetWindowPos 来响应窗口大小调整事件。但是,实际按钮会保留在同一位置。我会发布屏幕截图,但由于某种原因,剪影从未出现在屏幕截图中。

这是更改 X 位置的代码(更改 Y 位置的代码几乎相同):

HRESULT Control::put_Left(float left)
{
    RECT windowRect;
    ::GetWindowRect(m_hWnd, &windowRect);
    if (m_isTopLevel)
    {
        BOOL bResult = ::SetWindowPos(
            m_hWnd,
            nullptr,
            static_cast<int>(DesktopDpi::GetInstance().DipsToPixelsX(left)),
            windowRect.top,
            0,
            0,
            SWP_NOSIZE | SWP_NOZORDER | SWP_NOREPOSITION
            );
        if (!bResult)
            return HRESULT_FROM_WIN32(::GetLastError());
    }
    else
    {
        // NOTE: for a button this is the code that will execute, because a
        // button is not a top-level window
        HWND hWndParent = ::GetParent(m_hWnd);
        if (hWndParent == nullptr)
            return HRESULT_FROM_WIN32(::GetLastError());
        POINT parentPos = {0, 0};
        if (!::ClientToScreen(hWndParent, &parentPos))
            return E_FAIL;
        BOOL bResult = ::SetWindowPos(
            m_hWnd,
            nullptr,
            static_cast<int>(DesktopDpi::GetInstance().DipsToPixelsX(left)),
            windowRect.top - parentPos.y,
            0,
            0,
            SWP_NOSIZE | SWP_NOZORDER | SWP_NOREPOSITION
            );
        if (!bResult)
            return HRESULT_FROM_WIN32(::GetLastError());
    }
    return S_OK;
}

您确定按钮的父级在处理WM_SIZE时没有将其移回旧位置吗? 从你的描述中听起来确实很像。