天天看點

VC 對編輯框的操作

       編輯框控件是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