单行编辑框文本垂直居中(包含计算字体高度)

单行编辑框文本垂直居中(包含计算字体高度)

有时为了界面更漂亮,使用高度比较高的编辑框,但单行文本的编辑框文字是靠上显示的,反而不美观了,使文本垂直居中有两种方法:

1. 属性设为多行,不接收换行,然后计算中间位置,使用SetRect设置到文本位置(注意OnSize还要处理)

可在Create、OnCreate、PreSubClass里处理

2. 响应WM_NCCALCSIZE修改客户区居中,通过获取字体高度计算

[cpp]  view plain copy
  1. void CEditEx::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS* lpncsp)  
    
    {  
    
     TRACE("Enter %s\n", __FUNCTION__);  
    
      
    
     CString cstrText(_T("字体test"));  
    
     SIZE sz;  
    
     GetTextExtentPoint32(GetDC()->GetSafeHdc(), cstrText, cstrText.GetLength(), &sz);  
    
       
    
     int nBorder = (lpncsp[0].rgrc->bottom - lpncsp[0].rgrc->top - sz.cy) / 2;  
    
     if(nBorder < 0)  
    
      nBorder = 0;  
    
     lpncsp[0].rgrc->top += nBorder;  
    
     lpncsp[0].rgrc->bottom -= nBorder;  
    
      
    
     CEdit::OnNcCalcSize(bCalcValidRects, lpncsp);  
    
    } 

 

两种方法都要用到计算字体高度,有3个函数可以使用:

GetTextExtentPoint32
GetTextExtent
GetTextMetrics

[cpp]  view plain copy
 
      CDC*   pDC=GetDC();     

      TEXTMETRIC   tm;     

      pDC->GetTextMetrics(&tm);     

      int   nHeight=tm.tmHeight+tm.tmExternalLeading;     

      int   nWidth=tm.tmAveCharWidth; 

 

你可能感兴趣的:(垂直居中)