There it hides behind your clouded brain...
There was this problem that I was working on which I think was pretty interesting. We are writing an application for a handheld device. Now there are textboxes in the application which we have to deal with. Now if the user wants to navigate from one textbox to its previous textbox, he has to press a combination of keys. Like for example Shift+S or Shift+B. this combination could be anything and is taken from a configuration file. Now the issue was this. Suppose it is Shift+S, when the user, used the combination, there was a capitalized S being printed in the textbox before the focus moved into the previous textbox.
Now we were handling the Key Up event of the textbox where we wrote code that would move the focus to the previous control. So when we did an e.Handled=true in the key up event, it didn’t work because the rendering was already done. The deadlines were short and everyone was in frenzy. So we didn’t really realize immediately what happened. So we left the issue open for a day.
Once we were done with things that were immediate in hand, I started looking into it. The solution was so simple, that I couldn’t believe it didn’t strike to me yesterday. When I started looking into it, I realized that the rendering was being done in the key press event. So if I want to disable it, I have to do an e.Handled=true in the key press event. There are two more events that I was looking into and that is Key up and Key down. Now Key down would be useful if you want to find the modifier keys. Key press event didn’t give me the modifier keys. So I couldn’t have found out whether the shift key is being pressed in the key press event. I would have to use the key down event for that.
So I was in a situation where key down would tell me whether the shift was pressed or not and key press would allow me to disable the rendering. So I declared a static Boolean variable IsShiftPressed which would be reset in all the 3 events. Key down, key up and key press. Once when the Shift Key is pressed, it would be set to true in the key down event. And in the key up event it would be set to false since now it is not in the state of being pressed. In the key press event I would check if the value of IsShiftPressed is true or not if it is then I would disable the rendering by doing a e.Handled=true.
The solution was that simple. When it didn’t come to me, I was getting all vague ideas like letting the system write the letter in the textbox and the clearing it, storing the whole value in a variable and then clearing it and then resetting the textbox.text property, etc. it is all a matter of perspective. So as they say, when things start getting heavy, you should cool down, but in a real life scenario, the exact opposite usually happens. And you become unable to see a solution that is staring right at your face.