Don't raise TextChanged while continuous typing

后端 未结 12 1230
闹比i
闹比i 2020-12-14 10:09

I have a textbox that has a fairly hefty _TextChanged event handler. Under normal typing condition the performance is okay, but it can noticeably lag when the u

12条回答
  •  时光说笑
    2020-12-14 10:33

    I don't know about culling the event queue, but I can think of two ways you may be able to handle this.

    If you want something quick (and slightly dirty by some people's standards), you could introduce a wait timer of sorts - when the validation function runs, set a flag (static variable within the function should suffice) with the current time. if the function is called again within say 0.5 seconds of the last time it ran and completed, exit the function immediately (dramatically reducing the runtime of the function). This will solve the backlog of events, provided it is the contents of the function that is causing it to be slow rather than the firing of the event itself. The downside to this is that you'd have to introduce a backup check of some sort to ensure that the current state has been validated - i.e., if the last change took place while a 0.5s block was happening.

    Alternatively, if your only problem is that you don't want the validation to occur when the user is engaging in a continuous action, you could try modifying your event handler such that it exits without performing the validation if a keypress is in progress, or maybe even bind the validation action to KeyUp rather than TextChanged.

    There are many ways in which you could achieve this. For example, if a KeyDown event is performed on a particular key (say backspace for your example, but in theory you should extend it to anything that will type a character), the validation function will exit without doing anything until the KeyUp event of the same key is fired. That way it won't run until the last modification has been made... hopefully.

    That may not be the most optimal way of achieving the desired effect (it may not work at all! There's a chance that the _TextChanged event will fire before the user has finished pressing the key), but the theory is sound. Without spending some time playing around I can't be absolutely sure on the behaviour of the keypress - can you just check whether the key is pressed and exit, or do you have to raise a flag manually that will be true between KeyDown and KeyUp? A little bit of playing around with your options should make it pretty clear what the best approach will be for your particular case.

    I hope that helps!

提交回复
热议问题