[Windows][C++]让窗口居中

#include <Windows.h>
#include <memory>
#include <string>
#include <crtdbg.h>

class WindowException:public std::exception
{
    std::string str{};
public:

    WindowException(_In_ std::string str):str(std::move(str))
    {
        
    }

    // 不应该忽略该返回值
    [[nodiscard("Exception info function")]]
    const char* what() const noexcept override
    {
        return this->str.c_str();
    }
};

auto CenterWindowF(_In_ const HWND& winHandle) -> void
{
    if (!winHandle)
        throw WindowException{ "Error:No Window handle" };	// 窗口句柄不应为空

    RECT rect{};
    GetWindowRect(winHandle, &rect);

    const auto width{ rect.right - rect.left };
    const auto height{ rect.bottom - rect.top };

    const auto cx{ GetSystemMetrics(SM_CXFULLSCREEN) }; // 取显示器屏幕高宽
    const auto cy{ GetSystemMetrics(SM_CYFULLSCREEN) };

    const auto x{ cx / 2 - width / 2 };
    const auto y{ cy / 2 - height / 2 };

    MoveWindow(winHandle, x, y, width, height,false); // 移动窗口位置居中
}

auto WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd) -> int
{
    constexpr auto winTitle{ L"Hello - Windows" };
    const auto winHandle{ FindWindow(nullptr,L"Debug") }; // 获取窗口句柄

    switch (const auto i{ MessageBox(winHandle, L"You need change window to center?", winTitle, MB_YESNOCANCEL | MB_ICONQUESTION | MB_TOPMOST ) }; i)
    {
    case IDOK:
        MessageBox(winHandle, L"You click Ok button", winTitle, MB_OK);
        break;
    case IDYES:
        try
        {
            CenterWindowF(winHandle);
        }
        catch (WindowException& winexc)
        {
            OutputDebugStringA("----------------------\n");
            OutputDebugStringA(winexc.what());
            OutputDebugStringA("\n----------------------\r\n");
        }
        SetWindowText(winHandle, L"Center!!!!");
        MessageBox(winHandle, L"Changed", winTitle, MB_OK);
        break;
    case IDNO:
        MessageBox(winHandle, L"Unchanged", winTitle, MB_OK);
        break;
    case IDCANCEL:
        MessageBox(winHandle, L"Cancel", winTitle, MB_OK);
        break;
    default:
        break;
    }

    _CrtDumpMemoryLeaks();	// 检查内存泄漏
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用Win32 API在C++中创建一个窗口并在父窗口居中显示的示例代码: ```c++ #include <Windows.h> // 窗口过程函数 LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // 主函数 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { // 注册窗口类 WNDCLASSEX wcex = { 0 }; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.lpszClassName = L"MyWindowClass"; RegisterClassEx(&wcex); // 创建主窗口 HWND hWnd = CreateWindowEx( WS_EX_CLIENTEDGE, L"MyWindowClass", L"My Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL); // 创建子窗口 HWND hChildWnd = CreateWindowEx( WS_EX_CLIENTEDGE, L"MyWindowClass", L"My Child Window", WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, 320, 240, hWnd, NULL, hInstance, NULL); // 获取主窗口和子窗口的客户区大小 RECT rcParent, rcChild; GetClientRect(hWnd, &rcParent); GetClientRect(hChildWnd, &rcChild); // 计算子窗口在父窗口中的位置 int xPos = (rcParent.right - rcParent.left - (rcChild.right - rcChild.left)) / 2; int yPos = (rcParent.bottom - rcParent.top - (rcChild.bottom - rcChild.top)) / 2; // 设置子窗口的位置 SetWindowPos(hChildWnd, NULL, xPos, yPos, 0, 0, SWP_NOSIZE | SWP_NOZORDER); // 显示窗口 ShowWindow(hWnd, nShowCmd); UpdateWindow(hWnd); // 消息循环 MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int)msg.wParam; } ``` 在上面的代码中,我们首先注册了一个窗口类,并创建了一个主窗口和一个子窗口。然后,我们获取了主窗口和子窗口的客户区大小,并计算出子窗口在父窗口中的位置,最后设置了子窗口的位置。最后,我们启动了消息循环,处理窗口消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

八宝咸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值