views:

200

answers:

3

In my .Net app, I keep running into the issue of a particular form/control which I expected to receive a keyboard event does not actually receive it. My debugging of this has not progressed much beyond caveman, eg setting breakpoints in all my controls, and seeing who ate a keyboard event that shouldn't have. There must be a better way - is there a tool out there which will help me trace the keyboard event handling?

+1  A: 

The first thing I would do is that I would check in the Properties window (or in the Designer file) to make sure that the event handler is indeed hooked up to the event.

Fredrik Mörk
Thanks, but I'm not that much of a noob =)
Not Sure
Good to hear; you said caveman so I thought that we start at the basics ;o)
Fredrik Mörk
A: 

Usually the form will handle the key press events. There's no tool because it's just monitoring your stack trace. The best idea would be to make a trace statement (add a breakpoint and right click, go to "When Hit") in your forms keypress event and then look at information in the forms.keyeventargs and sender objects.

Other important items to note: non-character keys (including page down, page up, etc.) do not raise a keypress event, they only raise keydown and keyup, keypress events are "swallowed" by the form if you set

e.Handled = true;

or

e.SuppressKeyPress = true;

I also don't recommend using the designer/properties window to hook up your events, use Addhandler (VB) or += (C#) because in more complex forms you will have scenarios of many controls sharing event handlers, and dynamically specifying handlers at runtime.

marr75
You can easily have shared event handlers even if you use the Properties window to attach the event handlers.
Fredrik Mörk
A: 

Assuming you're using a full version of Visual Studio (not the Express edition or anything else) use Spy++. When you start up Spy++ locate your application root window (Spy++ has a handy Search > Find Window menu item to help) then right click the root window in the Windows tree view and select Messages. This should bring you to the messages pane which will begin monitoring all messages for the window. Begin typing and check for WM_KEYDOWN etc. If you still don't see your key presses go to messaging options and check "Windows of Same Process". At this point you should be able to monitor all keypress events in the process. Right click on a WM_KEYDOWN (or similar) message and go to properties. In the properties the handle of the window that handled the message should be displayed and clicking on it will highlight it in the Windows tree view. Now all you have to do is right click on the highlighted window and select Highlight to see which control it is on your form.

Corillian