Wednesday, February 23, 2011

Handling KeyPress at Form level

I don’t think this will help a experienced Win Forms developer. But it will help a fresher.

Here is the story.One of my colleague is developing a simple tool and he wanted to capture key strokes such as Ctrl+K,C like Visual studio.The plat form is windows forms and he handled the KeyDown event at form Level. But the break point didn't hit because the focus is always on any of the UI controls present in the form. He started seeking help on the title ”The Form is not getting key press or key down if there are any controls”

As usual we started thinking in complicated ways. The reason was concluded as “The form is not getting focus that is why its not able to catch the key press”. One suggestion was to override the ProcessCmdKey and write the code there. Another one went more deeper. Override the WndProc and handle directly.

But after a tea break we could see that there is one property in the Form named KeyPreview and just need to set that to True in order to get the key events.

Moral of the story

You will never think about a completely different solution unless you take a TEA BREAK.There will be always a simple solution.

No comments: