Skip to content

Instantly share code, notes, and snippets.

@l2m2
Last active Sep 7, 2021
Embed
What would you like to do?
Duilib-基于CEditUI实现可限制输入范围的数字编辑框
class NumberEditUI : public CEditUI {
public:
NumberEditUI() : CEditUI()
{
this->OnNotify += DuiLib::MakeDelegate(this, &NumberEditUI::OnTextChanged);
}
protected:
virtual void SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue) override
{
if (_tcsicmp(pstrName, _T("min")) == 0) {
m_min = _tstof(pstrValue);
m_bValidateMin = true;
}
else if (_tcsicmp(pstrName, _T("max")) == 0) {
m_max = _tstof(pstrValue);
m_bValidateMax = true;
}
else {
CEditUI::SetAttribute(pstrName, pstrValue);
}
}
bool OnTextChanged(PVOID param)
{
TNotifyUI *event = (TNotifyUI *)param;
if (event->sType != DUI_MSGTYPE_TEXTCHANGED) return true;
CDuiString text = this->GetText();
regex rx(R"((?:^|\s)[+-]?(([[:digit:]]+(?:\.[[:digit:]]*)?))?(?=$|\s))");
if (text.IsEmpty()) goto VALID;
if (!std::regex_match(FrameUtils::wstring2string(text.GetData()), rx)) goto INVALID;
double current = _tstof(text.GetData());
if (m_bValidateMin && (current < m_min)) goto INVALID;
if (m_bValidateMax && (current > m_max)) goto INVALID;
VALID:
m_oldValue = text;
return true;
INVALID:
this->SetText(m_oldValue);
this->SetSel(m_oldValue.GetLength(), m_oldValue.GetLength());
return true;
}
protected:
double m_min, m_max;
bool m_bValidateMin = false, m_bValidateMax = false;
CDuiString m_oldValue;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment