Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows forms Text Changed on leave event

Maybe I'm just an idiot, but I can't seem to find an event that will fire for a textbox at the same time as the leave, but only when the contents of the textbox has changed. Kinda like a combination of textchanged and leave. I can't use textchanged cause it fires on each keystroke. Right now I'm storing the current value of the textbox in a variable and comparing it on the leave event, but it seems really hackish.

Thanks

like image 427
Rob Avatar asked Jan 23 '23 16:01

Rob


2 Answers

You can create your own (derived) class which overrides OnEnter, OnLeave and OnTextChanged to set flags and trigger "your" event.

Something like this:

    public class TextBox: System.Windows.Forms.TextBox {
        public event EventHandler LeaveWithChangedText;

        private bool textChanged;

        protected override void OnEnter(EventArgs e) {
            textChanged = false;
            base.OnEnter(e);
        }

        protected override void OnLeave(EventArgs e) {
            base.OnLeave(e);
            if (textChanged) {
                OnLeaveWithChangedText(e);
            }
        }

        protected virtual void OnLeaveWithChangedText(EventArgs e) {
            if (LeaveWithChangedText != null) {
                LeaveWithChangedText(this, e);
            }
        }

        protected override void OnTextChanged(EventArgs e) {
            textChanged = true;
            base.OnTextChanged(e);
        }
    }
like image 127
Lucero Avatar answered Jan 26 '23 04:01

Lucero


The answer of @Lucero does it's job almost perfectly.
However, it does not handle the case when a user edits the text and finally enters the same value as before. Therefore I created a similar solution for my own (in C++/CLI, but you can easily adapt it to C#):

public ref class EventArgsCTextBox1 : EventArgs
{
public:
  String^ PreviousText;
};

public ref class CTextBox1 : Windows::Forms::TextBox
{
public:
  virtual void OnEnter (EventArgs^ i_oEventArgs) override;
  virtual void OnLeave (EventArgs^ i_oEventArgs) override;

  delegate void EventHandlerCTextBox1 (Object^ i_oSender, EventArgsCTextBox1^ i_oEventArgs);
  event EventHandlerCTextBox1^ LeaveChanged;

private:
  String^ m_sValue;
};

void CTextBox1::OnEnter (System::EventArgs^ i_oEventArgs)
{
  TextBox::OnEnter (i_oEventArgs);
  m_sValue = this->Text;
}

void CTextBox1::OnLeave (System::EventArgs^ i_oEventArgs)
{
  TextBox::OnLeave (i_oEventArgs);
  if (m_sValue != this->Text)
  {
    EventArgsCTextBox1^ oEventArgs = gcnew EventArgsCTextBox1;
    oEventArgs->PreviousText = m_sValue;
    LeaveChanged (this, oEventArgs);
  }
}
like image 39
Tobias Knauss Avatar answered Jan 26 '23 04:01

Tobias Knauss