【发布时间】:2012-12-05 08:11:09
【问题描述】:
在 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;
}
【问题讨论】:
-
请忽略我的原始答案(如果它仍然在下面),因为我误读了您的问题。如果您看到按钮短暂移动然后返回到原来的位置,您确定您的
put_Left函数没有被调用两次吗?我会输入一些OutputDebugString调用以打印出传递给SetWindowPos的坐标,并查看按钮的确切位置。