#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;
}
[Windows][C++]让窗口居中
最新推荐文章于 2023-09-27 11:08:14 发布