Quite often when I make VCL programs, I run into a scenario like this:
Now what I want is that whenever the user is typing something in the TEdit::Text, the OnChange event must process the user input. But when my program is setting the TEdit::Text to a default value, this isn't necessary, because then I know that the value is correct.
Unfortunately, writing code like myedit->Text = "Default";
triggers the OnChange event.
I tend to solve this with what I think is a rather ugly approach: by creating a bool variable is_user_input
, which TEdit::OnChange
checks. If it is true, the TEdit::Text will get validated, otherwise it will get ignored. But of course, this doesn't prevent the program from launching TEdit::OnChange
when it is unnecessary.
Is there a better or cleaner way to achieve this?
Is there a way for OnChange to check who called it? Or I suppose, a way of disabling the OnChange event temporarily would be even better. TEdit::Enabled
doesn't seem to affect whether OnChange
gets triggered or not.
You could simply unassign the OnChange
event handler temporarily:
template <typename T>
void SetControlTextNoChange(T *Control, const String &S)
{
TNotifyEvent event = Control->OnChange;
Control->OnChange = NULL;
try {
Control->Text = S;
}
__finally {
Control->OnChange = event;
}
}
SetControlTextNoChange(myedit, "Default");
Alternatively, RAII is good for this kind of thing:
template <typename T>
class DisableChangeEvent
{
private:
T *m_control;
TNotifyEvent m_event;
public:
DisableChangeEvent(T *control);
{
m_control = control;
m_event = control->OnChange;
control->OnChange = NULL;
}
~DisableChangeEvent();
{
m_control->OnChange = m_event;
}
T* operator->() { return m_control; }
};
DisableChangeEvent(myedit)->Text = "Default";