存档

文章标签 ‘居中’

win32 程序窗体居中

2015年12月20日 没有评论

C#对于窗体居中很简单,只需要简单设置一个属性就可以了,但是对于C++,还需要额外的写点代码。下面是衣服自己洗分享的代码,可以直接拷贝到项目中。

inline static BOOL CenterWindow(HWND hwndWindow,bool isDesktopParent = true)
{
HWND hwndParent;
RECT rectWindow, rectParent;

hwndParent = isDesktopParent ? GetDesktopWindow() : GetParent(hwndWindow);

//make the window relative to its parent
if (hwndParent != nullptr)
{
GetWindowRect(hwndWindow, &rectWindow);
GetWindowRect(hwndParent, &rectParent);

int nWidth = rectWindow.right – rectWindow.left;
int nHeight = rectWindow.bottom – rectWindow.top;

int nX = ((rectParent.right – rectParent.left) – nWidth) / 2 + rectParent.left;
int nY = ((rectParent.bottom – rectParent.top) – nHeight) / 2 + rectParent.top;

int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);

//make sure the window never moves outside of the screen
if (nX < 0) nX = 0;
if (nY < 0) nY = 0;
if (nX + nWidth > nScreenWidth) nX = nScreenWidth – nWidth;
if (nY + nHeight > nScreenHeight) nY = nScreenHeight – nHeight;

MoveWindow(hwndWindow, nX, nY, nWidth, nHeight, FALSE);

return TRUE;
}

return FALSE;
}

分类: C++, 一句话 标签: ,