我把CStatic重写了一下,我想在设置文字(setwindowtext)的时候让控件的大小随文字的长度改变大小(现在仅考虑单行)
void CMyStatic::SetWindowText(LPCTSTR lpszString ) //设置文字
{
CString str=lpszString;
if (str!="")
{
CClientDC dc(this);
CRect rc;
GetWindowRect(&rc);
CSize sz=dc.GetOutputTextExtent(str); //获取字符串信息
rc.left=rc.CenterPoint().x-sz.cx/2-1;
rc.top=rc.CenterPoint().y-sz.cy/2-1;
// ScreenToClient(&rc);
MoveWindow(rc.left,rc.top,sz.cx+1,sz.cy+1);
}
CStatic::SetWindowText(str);
}
假设有一个按钮,我想点击的时候改变文字,可是一点击控件就消失了,如果不注释上面的ScreenToClient(&rc);
除了位置不正确外文字和大小改变都成功了,为什么啊?
void CMyStatic::SetWindowText(LPCTSTR lpszString ) //设置文字
{
CString str=lpszString;
if (str!="")
{
CClientDC dc(this);
CRect rc;
GetWindowRect(&rc);
CSize sz=dc.GetOutputTextExtent(str); //获取字符串信息
rc.left=rc.CenterPoint().x-sz.cx/2-1;
rc.top=rc.CenterPoint().y-sz.cy/2-1;
// ScreenToClient(&rc);
MoveWindow(rc.left,rc.top,sz.cx+1,sz.cy+1);
}
CStatic::SetWindowText(str);
}
假设有一个按钮,我想点击的时候改变文字,可是一点击控件就消失了,如果不注释上面的ScreenToClient(&rc);
除了位置不正确外文字和大小改变都成功了,为什么啊?
换成GetParent()->ScreenToClient(&rc);
void CMyStatic::SetWindowText(LPCTSTR lpszString ) //设置文字
{
CString str=lpszString;
if (str!="")
{
CClientDC dc(this);
CRect rcMe;
GetWindowRect(&rcMe);
CSize sz=dc.GetOutputTextExtent(str); //获取字符串信息
if (rcMe.Width()!=sz.cx || rcMe.Height()!=sz.cy)
{
CRect rcParentClient,rcParentWhole;
GetParent()->GetClientRect(&rcParentClient);
GetParent()->GetWindowRect(&rcParentWhole);
int CaptionH=0;
int CaptionW=0;
if (rcParentClient.right!=rcParentWhole.Width() || rcParentClient.bottom!=rcParentWhole.Height())
{
CaptionH=rcParentWhole.Height()-rcParentClient.bottom-3;
CaptionW=rcParentWhole.Width()-rcParentClient.right-3;
//CaptionW= GetSystemMetrics(SM_CXFRAME);
//CaptionH= GetSystemMetrics(SM_CYCAPTION);
} if (m_ptCenter.x==0 && m_ptCenter.y==0)
{
m_ptCenter.x=rcMe.CenterPoint().x;
m_ptCenter.y=rcMe.top;
}
int x=m_ptCenter.x-sz.cx/2;
int y=m_ptCenter.y;
MoveWindow(x-rcParentWhole.left-CaptionW,y-rcParentWhole.top-CaptionH,sz.cx,sz.cy);
}
}
CStatic::SetWindowText(str);
}我现在改成如上:我的目的达到了
但是我不知道,为什么要减3,3是我试出来的
CaptionH=rcParentWhole.Height()-rcParentClient.bottom;
CaptionW=rcParentWhole.Width()-rcParentClient.right;
CaptionW= GetSystemMetrics(SM_CXFRAME);
CaptionH= GetSystemMetrics(SM_CYCAPTION);
上面得到的结果依次是32,6,4,26,为什么不相等呢?????
3=主窗口边框2+子窗口边框1