Skip to content

Instantly share code, notes, and snippets.

@l2m2
Last active September 7, 2021 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save l2m2/909e44658a05d84d622e62efda645317 to your computer and use it in GitHub Desktop.
Save l2m2/909e44658a05d84d622e62efda645317 to your computer and use it in GitHub Desktop.
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