用SetWindowPos怎么设置窗口居中
用SetWindowPos如何设置窗口居中?
对话框程序,一开始便最大化的,还原后总是在屏幕左上角,用CenterWindow会闪烁,不知如何用SetWindowPos居中?
------解决方案--------------------
SetWindowPos() 需要计算当前屏幕大小,然后得到中间位置坐标等
------解决方案--------------------
CenterWindow也是调用SetWindowPos的
对话框程序,一开始便最大化的,还原后总是在屏幕左上角,用CenterWindow会闪烁,不知如何用SetWindowPos居中?
------解决方案--------------------
SetWindowPos() 需要计算当前屏幕大小,然后得到中间位置坐标等
------解决方案--------------------
CenterWindow也是调用SetWindowPos的
void CWnd::CenterWindow(CWnd* pAlternateOwner)
{
ASSERT(::IsWindow(m_hWnd));
// determine owner window to center against
DWORD dwStyle = GetStyle();
HWND hWndCenter = pAlternateOwner->GetSafeHwnd();
if (pAlternateOwner == NULL)
{
if (dwStyle & WS_CHILD)
hWndCenter = ::GetParent(m_hWnd);
else
hWndCenter = ::GetWindow(m_hWnd, GW_OWNER);
if (hWndCenter != NULL)
{
// let parent determine alternate center window
HWND hWndTemp =
(HWND)::SendMessage(hWndCenter, WM_QUERYCENTERWND, 0, 0);
if (hWndTemp != NULL)
hWndCenter = hWndTemp;
}
}
// get coordinates of the window relative to its parent
CRect rcDlg;
GetWindowRect(&rcDlg);
CRect rcArea;
CRect rcCenter;
HWND hWndParent;
if (!(dwStyle & WS_CHILD))
{
// don't center against invisible or minimized windows
if (hWndCenter != NULL)
{
DWORD dwAlternateStyle = ::GetWindowLong(hWndCenter, GWL_STYLE);
if (!(dwAlternateStyle & WS_VISIBLE)
------解决方案--------------------
(dwAlternateStyle & WS_MINIMIZE))
hWndCenter = NULL;
}
MONITORINFO mi;
mi.cbSize = sizeof(mi);
// center within appropriate monitor coordinates
if (hWndCenter == NULL)
{
HWND hwDefault = AfxGetMainWnd()->GetSafeHwnd();
GetMonitorInfo(
MonitorFromWindow(hwDefault, MONITOR_DEFAULTTOPRIMARY), &mi);
rcCenter = mi.rcWork;
rcArea = mi.rcWork;
}
else
{
::GetWindowRect(hWndCenter, &rcCenter);
GetMonitorInfo(
MonitorFromWindow(hWndCenter, MONITOR_DEFAULTTONEAREST), &mi);
rcArea = mi.rcWork;
}
}
else
{
// center within parent client coordinates
hWndParent = ::GetParent(m_hWnd);
ASSERT(::IsWindow(hWndParent));
::GetClientRect(hWndParent, &rcArea);
ASSERT(::IsWindow(hWndCenter));
::GetClientRect(hWndCenter, &rcCenter);
::MapWindowPoints(hWndCenter, hWndParent, (POINT*)&rcCenter, 2);
}
// find dialog's upper left based on rcCenter
int xLeft = (rcCenter.left + rcCenter.right) / 2 - rcDlg.Width() / 2;
int yTop = (rcCenter.top + rcCenter.bottom) / 2 - rcDlg.Height() / 2;
// if the dialog is outside the screen, move it inside
if (xLeft + rcDlg.Width() > rcArea.right)
xLeft = rcArea.right - rcDlg.Width();
if (xLeft < rcArea.left)