MFC - 删除CEdit编号控制的前导零

时间:2017-08-18 03:34:27

标签: c++ mfc

我发现CEdit控件在其属性中有选项'Number',这样我就可以阻止用户在此文本框中输入非数字字符 - 它现在是CEdit控件。 如果有一个选项'Number',我想可能有一种方法可以删除CEdit的前导零,这就像选项'Number'一样简单。

我已经尝试Dialog Data Exchange,希望能自动删除前导零,但不会。

然后我认为这样做的方法是为每个CEdit号码控件添加EN_KILLFOCUS消息,但我觉得用尽了。

所以我认为更好的方法是添加EN_KILLFOCUS,但是所有CEdit数控制都将焦点事件指向一个函数,在这个函数中我将删除'当前'控件的前导零,但在C#中可以获得'当前'控件,在C ++中我不知道它是否受支持。

或继承CEdit使CEditNum - 实现失去焦点删除前导零功能,但使用此解决方案,我无法在Visual Studio设计窗口(我认为)设计它。我希望有一个类似于this solution的解决方案(这是Draw& Drop问题的解决方案)

无论如何,在应用最终解决方案(EN_KILLFOCUS)之前,我想确定是否有更好的方法 - 最少实现,重用现有的MFC工具。

关于删除前导零的一点解释:你输入:00001进入CEdit控件,然后失去焦点,CEdit控件显示:1。当你在其单元格中输入一个数字时,这个想法就像MS Excel。

1 个答案:

答案 0 :(得分:0)

  

"但所有CEdit号码控件都将焦点事件指向一个功能"

这是事实,但是你得到的控件的控件ID只是失去了作为参数的焦点。

将此添加到您的Message表中,将IDC_FIRST,IDC_LAST替换为编辑控件的第一个和最后一个ID,或者对所有ID使用0,0xFFFFFFFF。

ON_CONTROL_RANGE(EN_KILLFOCUS, IDC_FIRST, IDC_LAST, OnKillFocus). 

这是OnKillFocus的签名,以及如何让CWnd应用更改。

void CMyDialogClass::OnKillFocus(UINT nID) 
{
    // you can further check if the ID is one of interest here...
    // if your edit control control IDs are not contiguous, for example.

    // you can get a CEdit* here, but only if you used DDX to map the 
    // control to a CEdit.  
    CWnd* pCtrl = GetDlgItem(nID);
    if (pCtrl)
    {
        CString str;
        pCtrl->GetWindowText(str);
        // remove zeroes, or format as you like....
        str.Format(_T("%d"), _tcstoi(str));
        pCtrl->SetWindowText(str);
    }
}

// if you mapped the control to a CEdit, here's how you can safely          
// get a pointer to a CEDit

CEdit* pEdit = (CEdit*)GetDlgItem(nID);
ASSERT_KINDOF(CEdit, pEdit);  // debug check
if (pEdit && pEdit->IsKindOf(RUNTIME_CLASS(CEdit)))  // standard check
{
// ....
}