[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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

八宝咸鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值