如何将对话框位置坐标复制到另一个对话框中?

How can I copy a dialogs position coordinates into another dialogs?

我有几个独特的按钮,一次只想显示其中一个。我希望它们居中,所以我将第一个按钮置于对话框的中心。如果我想显示第三个按钮,我想给它第一个按钮坐标并隐藏第一个按钮。

如何复制一个按钮坐标并将另一个按钮坐标设置为复制的值?

例如。假设我有...

PB_ONE
PB_TWO

如何获取PB_ONE的坐标并将PB_TWO的坐标设置为PB_ONE?

RECT rcButton;

GetWindowRect(GetDlgItem(hDlg, PB_ONE), &rcButton);

以上代码获取了我要从中复制坐标的对话框项。是否有一个简单的命令可以将另一个对话框按钮设置为该对话框坐标?

类似 SetDlgItem() 的东西?

更新了我根据答案尝试的新代码

GetWindowRect(GetDlgItem(hDlg, PB_ONE), &rcButton);
ClientToScreen(hDlg, &p);
OffsetRect(&rcButton, -p.x, -p.y);
SetWindowPos(GetDlgItem(hDlg, PB_TWO), 0, rcButton.left, rcButton.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
ShowWindow(GetDlgItem(hDlg, PB_TWO), SW_SHOW);

当前必须将 rcButton.left 和 rcButton.top 替换为 p.x 以及 rcButton.top 的硬值,以便让按钮在对话框屏幕上定位。

这 returns SetWindowPos 中的一个错误,其中参数 3 无法将 LONG * 转换为 INT。

GetWindowRect 给出屏幕坐标中的矩形。您可以使用 ScreenToClient(HWND hWnd, LPPOINT lpPoint) 将其转换为客户坐标。


编辑:

RECT rcButton;
HWND hbutton1 = GetDlgItem(hDlg, PB_ONE);
HWND hbutton2 = GetDlgItem(hDlg, PB_TWO);

//if(!hbutton1 || !hbutton2) {error...}

GetWindowRect(hbutton1, &rcButton);

//Test
char buf[50];
sprintf(buf, "%d %d", rcButton.left, rcButton.top);
MessageBoxA(0, buf, "screen coord", 0);

//Note, this will only convert the top-left corner, not right-bottom corner
//but that's okay because we only want top-left corner in this case
ScreenToClient(hDlg, (POINT*)&rcButton);

//Test
sprintf(buf, "%d %d", rcButton.left, rcButton.top);
MessageBoxA(0, buf, "client coord", 0);

ShowWindow(hbutton1, SW_HIDE);
SetWindowPos(hbutton2, 0, rcButton.left, rcButton.top, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW);


稍微简单一点的方法是使用 ClientToScreen(HWND hWnd, LPPOINT lpPoint) 如下:

RECT rcButton;
GetWindowRect(GetDlgItem(hDlg, PB_ONE), &rcButton);

POINT p{ 0 };
ClientToScreen(hDlg, &p);
//p is now (0,0) of parent window in screen coordinates
OffsetRect(&rcButton, -p.x, -p.y);

rcButton 现在是相对于父 window 左上角的坐标。您可以在 SetWindowPos 中使用它。