工控编程吧

标题: 上位机MFC如何限制编辑框输入文本的长度 [打印本页]

作者: qq263946146    时间: 2019-7-27 17:21
标题: 上位机MFC如何限制编辑框输入文本的长度
编辑框输入文本的多少可以通过函数LimitText 来设置。
此函数可以设置输入编辑内字节的个数。
默认值为UINT_MAX。
可以查询手册,有具体介绍:
void LimitText( int nChars = 0 );
Parameters
nChars
Specifies the length (in bytes) of the text that the user can enter. If this parameter is 0, the text length is set to UINT_MAX bytes. This is the default behavior.
Remarks
Call this function to limit the length of the text that the user may enter into an edit control.
Changing the text limit restricts only the text the user can enter. It has no effect on any text already in the edit control, nor does it affect the length of the text copied to the edit control by the SetWindowText member function in CWnd. If an application uses the SetWindowText function to place more text into an edit control than is specified in the call to LimitText, the user can delete any of the text within the edit control. However, the text limit will prevent the user from replacing the existing text with new text, unless deleting the current selection causes the text to fall below the text limit.


假设我们有一个编辑框控件IDC_EDIT1.
我们可以在程序初始化时调用下面代码设置编辑框输入内容长度。
然后在运行程序查看编辑框能输入多少字节。
  1. //获得编辑框的字体大小
  2.         CEdit *pWnd = (CEdit *)GetDlgItem(IDC_EDIT1);
  3.         TEXTMETRIC tm;
  4.         CDC* pDC = pWnd->GetDC();
  5.         pDC->GetTextMetrics(&tm);
  6.         pWnd->ReleaseDC(pDC);

  7.         //获得编辑框的格式化矩形
  8.         CRect rect;
  9.         pWnd->GetRect(&rect);

  10.         pWnd->LimitText(rect.Width() / tm.tmAveCharWidth);
复制代码


[MFC408]1[/MFC408]
[weixinlianxi]1[/weixinlianxi]






欢迎光临 工控编程吧 (https://www.gkbc8.com/) Powered by Discuz! X3.4