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

前端 未结 15 1276
无人及你
无人及你 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:22

    If user is typing fast and you want to delay the calculation until he stopped typing then below code may help:

    private void valueInput_TextChanged(object sender, EventArgs e)
    {
        CalculateAfterStopTyping();   
    }
    
    Thread delayedCalculationThread;
    
    int delay = 0;
    private void CalculateAfterStopTyping()
    {
        delay += 200;
        if (delayedCalculationThread != null && delayedCalculationThread.IsAlive)
            return;
    
        delayedCalculationThread = new Thread(() =>
        {
            while (delay >= 200)
            {
                delay = delay - 200;
                try
                {
                    Thread.Sleep(200);
                }
                catch (Exception) {}
            }
            Invoke(new Action(() =>
            {
                // do your calcualation here...
            }));
        });
    
        delayedCalculationThread.Start();
    }
    

提交回复
热议问题