1. 获取屏幕大小
方法I:使用GetSystemMetrics()
int nWidth = GetSystemMetrics(SM_CXSCREEN); int nHeight = GetSystemMetrics(SM_CYSCREEN);
得到1920*1080
例如:实现窗口居中显示
//屏幕大小 int cx = GetSystemMetrics(SM_CXSCREEN); int cy = GetSystemMetrics(SM_CYSCREEN); //窗口居中 CRect rt; GetWindowRect(&rt); SetWindowPos(NULL, (cx - rt.Width()) / 2, (cy - rt.Height()) / 2, 0, 0, SWP_NOSIZE); //或者用MoveWindow() MoveWindow((cx - rt.Width())/2, (cy - rt.Height())/2, rt.Width(), rt.Height());
例如:动态创建的窗口并居中显示:
//创建窗口 //m_clsInstDlg.DoModal(); //不要用模态窗口,会阻塞程序 m_clsInstDlg.Create(IDD_INSTALL_DIALOG, GetDlgItem(IDD_MENU_DIALOG)); m_hInstDlg = m_clsInstDlg.m_hWnd; //设置标题 m_clsInstDlg.SetTitle(m_strResCfg.sResName); //窗口居中 int cx = GetSystemMetrics(SM_CXSCREEN); int cy = GetSystemMetrics(SM_CYSCREEN); CRect rt; m_clsInstDlg.GetWindowRect(&rt); m_clsInstDlg.SetWindowPos(NULL, (cx - rt.Width()) / 2, (cy - rt.Height()) / 2, 0, 0, SWP_NOSIZE); //显示窗口 m_clsInstDlg.ShowWindow(SW_SHOW);
方法II: 使用GetDesktopWindow(), GetWindowRect()
</pre><pre name="code" class="cpp">GetDesktopWindow()->GetWindowRect(m_DesktopRect); int nWidth = m_DesktopRect.Width() int nHeight = m_DesktopRect.Height();
2. 获取桌面大小
CRect rectWorkArea; SystemParametersInfo(SPI_GETWORKAREA, 0, &rectWorkArea, SPIF_SENDCHANGE); int nWidth = rectWorkArea.Width(); int nHeight = rectWorkArea.Height();
得到 1920*1040(不包括任务栏的高度)
例如:实现桌面居中显示
//桌面大小 CRect rectWorkArea; SystemParametersInfo(SPI_GETWORKAREA, 0, &rectWorkArea, SPIF_SENDCHANGE); //桌面大小 //窗口居中 CRect rt; GetWindowRect(&rt); int nX = (rectWorkArea.Width() - rt.Width()) / 2; int nY = (rectWorkArea.Height() - rt.nHeight()) / 2; SetWindowPos(NULL, nX, nY, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOREDRAW); //不要添加SWP_NOMOVE(会忽略坐标设置)
时间: 2024-10-05 04:26:01