C# wait for user to finish typing in a Text Box

前端 未结 15 1260
无人及你
无人及你 2020-11-27 18:16

Is there a way in C# to wait till the user finished typing in a textbox before taking in values they have typed without hitting enter?

Revised this question a little

15条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 18:35

    Ideally an inheritance solution like esskar’s is the way to go but it doesn’t play well with the designer so to get the re-use I opted for a helper style side-class:

    using System;
    using System.Threading;
    using System.Windows.Forms;
    using Timer = System.Threading.Timer;
    
        internal class DelayedText : IDisposable
        {
            private readonly EventHandler _onTextChangedDelayed;
            private readonly TextBox _textBox;
            private readonly int _period;
            private Timer _timer;
    
            public DelayedText(TextBox textBox, EventHandler onTextChangedDelayed, int period = 250)
            {
                _textBox = textBox;
                _onTextChangedDelayed = onTextChangedDelayed;
                _textBox.TextChanged += TextBoxOnTextChanged;
                _period = period;
            }
    
            public void Dispose()
            {
                _timer?.Dispose();
                _timer = null;
            }
    
            private void TextBoxOnTextChanged(object sender, EventArgs e)
            {
                Dispose();
                _timer = new Timer(TimerElapsed, null, _period, Timeout.Infinite);
            }
    
            private void TimerElapsed(object state)
            {
                _onTextChangedDelayed(_textBox, EventArgs.Empty);
            }
        }
    

    Usage, in the form constructor:

    InitializeComponent();
    ...
    new DelayedText(txtEdit, txtEdit_OnTextChangedDelayed);
    

    I haven't kicked it hard, but seems to work for me.

提交回复
热议问题