VC 对编辑框的操作

来源:互联网 发布:淘宝店铺个性公告范文 编辑:程序博客网 时间:2024/06/08 11:22

       编辑框控件是MFC使用频率较高的控件,本文主要介绍该控件的基本操作,包括改变背景、字体、文本颜色,长度限制、中英文字判断。

1、长度限制

在对话框初始化函数OnInitDialog()中:

m_edit1.SetLimitText(8);                           //m_edit1为编辑框的成员变量

或者

CEdit *pEdit=(CEdit *)GetDlgItem(IDC_EDIT1);   // IDC_EDIT1为控件ID
pEdit->SetLimitText(8);                              //限制编辑框输入长度为8字节

2、汉字判断

方法一、

CString str="hello世界";

for(int i=0;i<str.GetLength();i++)
{
       if(   (BYTE)str[i]   <   0x80 )
      {  
           MessageBox("非汉字");
     }      
    else      //汉字  
   {  
         MessageBox("是汉字");
    }                                                                    //方法不好,只能判断有没有汉字

方法二、

CString   ss="hello我的世界";
int i=0;
while(i<ss.GetLength())
{

   if(IsDBCSLeadByte(ss[i]))
    {

      //   是DBCS
       i += 2;
      AfxMessageBox("汉字");
      }

      else

    {

       //   英文
      i ++;
     AfxMessageBox("English");
    }
   }

3、字体及大小

定义一全局变量或成员变量CFont   font;                                        //不要定义成局部变量,否则没效果

CEdit *pEdit=(CEdit *)GetDlgItem(IDC_EDIT1);
font.CreatePointFont(266,"Arial");
pEdit->SetFont(&font);

4、改变背景及文本颜色

添加WM_CTLCOLOR消息的响应函数,然后在OnCtrlColor中

HBRUSH CMyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);

// TODO:  Change any attributes of the DC here
if(nCtlColor==CTLCOLOR_EDIT &&  pWnd->GetDlgCtrlID()==IDC_EDIT1)        //注意此处的(pWnd->),否则没效果
{
   pDC->SetTextColor(RGB(255,0,0));
   pDC->SetBkColor(RGB(255,255,0));// 设置文本背景色
   pDC->SetBkMode(TRANSPARENT);// 设置背景透明
}

// TODO:  Return a different brush if the default is not desired

return hbr;
}

对于nCtlColor的类型,如下:

CTLCOLOR_BTN                  Button control
CTLCOLOR_DLG                  Dialog box
CTLCOLOR_EDIT                  Edit control
CTLCOLOR_LISTBOX           List-box control
CTLCOLOR_MSGBOX           Message box
CTLCOLOR_SCROLLBAR    Scroll-bar control
CTLCOLOR_STATIC              Static control

 

原创粉丝点击