MFC 界面自动调整适应不同分辨率

3 篇文章 0 订阅

首先获取界面对话框的原始尺寸

Rect recta;
GetClientRect(&recta);     //取客户区大小  
m_oldPoint.x = recta.right - recta.left;  //m_oldPoint是成员变量,用于保存上一次的界面尺寸
m_oldPoint.y = recta.bottom - recta.top;

再获取电脑屏幕分辨率,并将对话框在屏幕上作一个合适的位置调整

int screenwidth = GetSystemMetrics(SM_CXFULLSCREEN);//获取屏幕分辨率宽度,不包括任务栏等区域
int screenheight = GetSystemMetrics(SM_CYFULLSCREEN);//获取屏幕分辨率高度,不包括任务栏等区域
CRect rect(screenwidth / 20, screenheight / 20, (screenwidth / 20) * 19, (screenheight / 20) * 19);   //设置对话框在屏幕上显示的位置   
CWnd * pWnd = AfxGetMainWnd();
pWnd->MoveWindow(rect);

由于对话框进行了调整,所以对话框的各个空间都要进行相应的调整:

void CMFCTestDlg::ReSize()
{
	float fsp[2];
	POINT Newp; //现在对话框的大小
	CRect recta;
	GetClientRect(&recta);     //取客户区大小  
	Newp.x = recta.right - recta.left;
	Newp.y = recta.bottom - recta.top;
	fsp[0] = (float)Newp.x / m_oldPoint.x;
	fsp[1] = (float)Newp.y / m_oldPoint.y;
	CRect Rect;
	int woc;
	CPoint OldTLPoint, TLPoint; //左上角
	CPoint OldBRPoint, BRPoint; //右下角
	HWND  hwndChild = ::GetWindow(m_hWnd, GW_CHILD);  //列出所有控件  
	while (hwndChild)
	{
		woc = ::GetDlgCtrlID(hwndChild);//取得ID
		GetDlgItem(woc)->GetWindowRect(Rect);
		ScreenToClient(Rect);

		OldTLPoint = Rect.TopLeft();
		TLPoint.x = long(OldTLPoint.x * fsp[0]);
		TLPoint.y = long(OldTLPoint.y * fsp[1]);
		OldBRPoint = Rect.BottomRight();
		BRPoint.x = long(OldBRPoint.x * fsp[0]);
		BRPoint.y = long(OldBRPoint.y * fsp[1]);
		Rect.SetRect(TLPoint, BRPoint);

		GetDlgItem(woc)->MoveWindow(Rect, TRUE);  //控件自适应
		hwndChild = ::GetWindow(hwndChild, GW_HWNDNEXT);
	}
	m_oldPoint = Newp;
}

只要对话框调整了,就可以调用ReSize()对控件进行调整

PS:通常光是控件自适应调整是不够的,控件上显示的字体也要自适应调整。可以将下方代码加入到控件自适应后面

        char sControlClassName[MAX_PATH] = { 0 };
		GetClassNameA(hwndChild, sControlClassName, MAX_PATH);
		if (strcmp(sControlClassName, "Static") == 0 ||
			strcmp(sControlClassName, "Button") == 0)
		{
			CString sText;
			int iFontSize;  //常用分辨率下,比较合适的字体大小
			GetDlgItem(woc)->GetWindowText(sText);
			int iLength = sText.GetLength();
			
			int height = Rect.bottom - Rect.top;
			int width = Rect.right - Rect.left;
			CFont* pFont = GetDlgItem(woc)->GetFont();
			LOGFONT lf;
			pFont->GetLogFont(&lf);
			pFont->DeleteObject();
			lf.lfHeight = height * 4 / 5;
			iFontSize = 9;
			if((iLength * iFontSize) > width)
			{
				lf.lfWidth = width / iLength;
			}
			else
			{
				lf.lfWidth = iFontSize;
			}

			m_MainUIFont.CreateFontIndirect(&lf);
			GetDlgItem(woc)->SetFont(&m_MainUIFont);//控件字体自适应
			m_MainUIFont.Detach();
		}

最后再说明下CMFCTestDlg.h头文件里定义的几个变量和函数

POINT m_oldPoint; 
CFont m_MainUIFont;
void ReSize();

  • 2
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值