桌面应用程序c++当点击“位置”菜单项时:正方形中心位置移至窗口中心
时间: 2023-09-15 11:19:38 浏览: 51
好的,如果您使用的是桌面应用程序,可以使用Win32 API来实现正方形的移动。您可以在菜单项的消息处理函数中添加如下代码来实现:
```c++
// 获取正方形的句柄
HWND hSquare = GetDlgItem(hwnd, IDC_SQUARE);
// 获取当前窗口的客户区尺寸
RECT clientRect;
GetClientRect(hwnd, &clientRect);
// 获取正方形的尺寸
RECT squareRect;
GetWindowRect(hSquare, &squareRect);
ScreenToClient(hwnd, reinterpret_cast<POINT*>(&squareRect.left));
ScreenToClient(hwnd, reinterpret_cast<POINT*>(&squareRect.right));
ScreenToClient(hwnd, reinterpret_cast<POINT*>(&squareRect.top));
ScreenToClient(hwnd, reinterpret_cast<POINT*>(&squareRect.bottom));
// 计算正方形的中心位置
int x = (clientRect.right - clientRect.left - squareRect.right + squareRect.left) / 2;
int y = (clientRect.bottom - clientRect.top - squareRect.bottom + squareRect.top) / 2;
// 移动正方形到窗口中心
SetWindowPos(hSquare, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
```
上述代码中,`hwnd`是当前窗口的句柄,`IDC_SQUARE`是正方形控件的ID,您需要根据实际情况进行替换。这里首先获取了正方形的句柄,然后获取当前窗口的客户区尺寸,接着获取正方形的尺寸,并计算出正方形的中心位置,最后通过API函数`SetWindowPos`将正方形移动到窗口的中心位置。