首先获取界面对话框的原始尺寸
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();