Last active
September 7, 2021 01:54
-
-
Save l2m2/909e44658a05d84d622e62efda645317 to your computer and use it in GitHub Desktop.
Duilib-基于CEditUI实现可限制输入范围的数字编辑框
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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