Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay KeyUp Action if User is Typing (C#)

I have a function that is being called when the user is typing in a search box. I want to wait for the user to finish typing before I actually execute the function. I know how to easily accomplish this in JavaScript with timeouts, but how would I go about doing the same thing in C#? Also, how long should I wait before I assume the user is done typing? 100ms?

like image 609
Kirk Ouimet Avatar asked Dec 18 '22 00:12

Kirk Ouimet


1 Answers

If you're comfortable using the Reactive (Rx) framework, then you could implement this functionality using its built in throttling extremely quickly.

Here is an article on the subject: Rx Can Improve UI Responsiveness

And some code stolen & modified from the article:

var textObserver = (from text in Observable.FromEvent<TextChangedEventArgs>(_app.myTextField, "TextChanged")
   select text).Throttle(TimeSpan.FromSeconds(.5));

_searchObserver = textObserver.Subscribe(textChangedEvent =>
   {
      var tb = (TextBox)textChangedEvent.Sender;
      DoMySearch(tb.Text);
   });

As stated in the article (which is worth reading in full), this will fire the code in the lambda expression whenever half a second elapses without the user typing anything.

I'll clean the example up tomorrow when I'm in front of my development PC, but this should give you a starting point now.

like image 151
Andrew Anderson Avatar answered Dec 30 '22 16:12

Andrew Anderson