获取屏幕及桌面大小

1. 获取屏幕大小

方法I:使用GetSystemMetrics()

int nWidth = GetSystemMetrics(SM_CXSCREEN);
int nHeight = GetSystemMetrics(SM_CYSCREEN);

得到1920*1080

注意:由于某些游戏会修改分辨率,所以会导致原本隐藏的窗口重现,建议使用方法2


例如:实现窗口居中显示

//屏幕大小
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()

GetDesktopWindow()->GetWindowRect(m_DesktopRect);  
int nWidth = m_DesktopRect.Width();
int nHeight = m_DesktopRect.Height();

得到1920*1080


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(会忽略坐标设置)


  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值