我把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);
除了位置不正确外文字和大小改变都成功了,为什么啊?

解决方案 »

  1.   

    你试试用GetTextExtent替换GetOutputTextExtent
      

  2.   

    For a child window, they are relative to the upper-left corner of the parent window's client area.子窗口的MoveWindow坐标是相对于父窗口
      

  3.   

      For a top-level CWnd object, the x and y parameters are relative to the upper-left corner of the screen. For a child CWnd object, they are relative to the upper-left corner of the parent window’s client area. 上面是msdn的一段话,意思是说MoveWindow时如果是子窗口,前面两个参数,坐标是相对于父窗口的客户区的。
      

  4.   

    把你的ScreenToClient(&rc);
    换成GetParent()->ScreenToClient(&rc);
      

  5.   


    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,为什么不相等呢?????

      

  6.   

    border 边框
    3=主窗口边框2+子窗口边框1