CEdit只能输入16进制数

1、创建CEDit继承类CEditEx,在继承类中处理字符响应函数,在CEdit控件上创建CEditEx控件变量,即可

BEGIN_MESSAGE_MAP(CEditEx, CEdit)
  // *****切记加入映射函数***** 
  ON_WM_CHAR()
END_MESSAGE_MAP()


BEGIN_DISPATCH_MAP(CEditEx, CEdit)
END_DISPATCH_MAP()

// Note: we add support for IID_IEditEx to support typesafe binding
//  from VBA.  This IID must match the GUID that is attached to the 
//  dispinterface in the .IDL file.

// {E869C413-CCF5-42DB-B86C-7EC5617ED3E5}
static const IID IID_IEditEx =
{ 0xE869C413, 0xCCF5, 0x42DB, { 0xB8, 0x6C, 0x7E, 0xC5, 0x61, 0x7E, 0xD3, 0xE5 } };

BEGIN_INTERFACE_MAP(CEditEx, CEdit)
    INTERFACE_PART(CEditEx, IID_IEditEx, Dispatch)
END_INTERFACE_MAP()


// CEditEx message handlers


void CEditEx::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) 
{ 
    if ( (nChar >= '0' && nChar <= '9') || 
        (nChar >= 'a' && nChar <= 'f') || 
        (nChar >= 'A' && nChar <= 'F') || 
        nChar == VK_BACK || 
        nChar == VK_DELETE) //msdn的virtual key
    { 
        nChar = (UINT)::CharUpperW(LPWSTR(nChar));                 //修改过的字母字符,转换为大写字母
        DefWindowProc(WM_CHAR, nChar, MAKELPARAM(nRepCnt, nFlags)); //用修改过的nChar调用
    } 
}

2、在控件上添加EN_CHANGE消息函数,然后对获取字符做处理
void Csigndata::OnEnChangeEnd()
{
    // TODO:  If this is a RICHEDIT control, the control will not
    // send this notification unless you override the CDialog::OnInitDialog()
    // function and call CRichEditCtrl().SetEventMask()
    // with the ENM_CHANGE flag ORed into the mask.

    // TODO:  Add your control notification handler code here
    CString strTemp=_T("");

    CEdit* editHelp = ((CEdit*)(GetDlgItem(IDC_END)));

    editHelp->GetWindowText(strTemp);

    int len = strTemp.GetLength();
    if (len > 4)
    {
        editHelp->SetWindowText(m_OldEndCode);
        return;
    }
    m_OldEndCode = strTemp;

    for (int i = 0; i < len; i ++)

    {
        char c = strTemp.GetAt(i);
        if(c < '0'||(c > '9'&& c < 'A')||c > 'F')

        {

            strTemp.Delete(i);
            m_OldEndCode.Delete(i);
            editHelp->SetWindowText(strTemp);

            editHelp->SetSel(i,i,TRUE);

            return;

        }

    }
}

你可能感兴趣的:(CEdit只能输入16进制数)