CEdit 文本垂直居中(单行解决方案)

转载自:https://blog.csdn.net/crybird/article/details/8959084

关于这个问题,网上流传的都是多行模仿,最后有附件,

由于怕细节不完美,决定探究下派生CEdit方法,可以响应WM_NCCALCSIZE消息,关键代码如下:

 
  1. void CVCenterEdit::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS* lpncsp)

  2. {

  3. CEdit::OnNcCalcSize(bCalcValidRects, lpncsp);

  4.  
  5. CClientDC dc(this);

  6. TEXTMETRIC tm;

  7. dc.GetTextMetrics(&tm);

  8. int nHeight = tm.tmHeight + tm.tmExternalLeading;

  9.  
  10. int n = (lpncsp->rgrc[0].bottom - lpncsp->rgrc[0].top - nHeight) / 2;

  11.  
  12. lpncsp->rgrc[0].top += n;

  13. lpncsp->rgrc[0].bottom -= n;

  14. }

问题1,上下空白背景不是白的。

解决方案:

BOOL CVCenterEdit::OnEraseBkgnd(CDC* pDC)

绘制WindowRect会覆盖边框,也可以留1-2像素让系统画,但根据系统不同很麻烦。

绘制ClientRect只画文字一行,不好。

唯有把整个对话框背景变成白色。或者处理对话框的OnEraseBkgnd,但代码比较多,耦合大。

(经网友shuren8提示,可以在OnNcPaint里绘制)

问题2,鼠标到上下空白的时候,光标是箭头而不是I,且边框无悬浮效果。

解决方案:响应消息WM_NCHITTEST,返回HTCLIENT。

问题3,无法触发WM_NCCALCSIZE消息。

解决方案:SubClass后调用MoveWindow等。例如BOOL CtestDlg::OnInitDialog() 中调用如下代码

m_edit.SetWindowPos(NULL,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_DRAWFRAME);

(网友shuren8的代码在VCenterEdit::CtlColor里面触发,确实很难找到一个完美的时间点触发,

好像有个第一次显示的消息,懒得深究了)

-----------------------------------------------------------------------------------------------------------

附件:(多行文本模仿法)

将文本框的属性设置为ES_MULTILINE | ES_AUTOHSCROLL且不能ES_AUTOVSCROLL | ES_WANTRETURN

http://blog.csdn.net/wincol/article/details/6198255

首先要设置为多行模式,去掉回车,滚动条等

  CRect rc; 
  m_ctlSearchBox.GetClientRect(&rc);
  CDC* pDC = m_ctlSearchBox.GetDC();
  TEXTMETRIC tm;
  pDC->GetTextMetrics(&tm);
  int nFontHeight = tm.tmHeight + tm.tmExternalLeading;
  int nMargin = (rc.Height() - nFontHeight) / 2;
  rc.DeflateRect(0,nMargin);
  m_ctlSearchBox.SetRectNP(&rc);

http://topic.csdn.net/t/20030606/14/1884129.html

http://hi.baidu.com/171808966/blog/item/0aaaa36e35878bd181cb4aaa.html

http://hi.baidu.com/dcrencq/blog/item/4bdb50c215f366130ff47722.html

http://topic.csdn.net/t/20030606/14/1884129.html

http://hi.baidu.com/171808966/blog/item/0aaaa36e35878bd181cb4aaa.html

http://hi.baidu.com/dcrencq/blog/item/4bdb50c215f366130ff47722.html

http://topic.csdn.net/t/20030606/14/1884129.html

http://hi.baidu.com/171808966/blog/item/0aaaa36e35878bd181cb4aaa.html

http://hi.baidu.com/dcrencq/blog/item/4bdb50c215f366130ff47722.html

猜你喜欢

转载自blog.csdn.net/ayang1986/article/details/81191279