views:

1014

answers:

2

Background: I have an application where I want to be able to capture keyboard events. On the main screen, the user clicks a Start button. During the game, the Start button goes away and a Reset button is shown (Visibility changes on the two controls). These are the only two standard controls involve as all else is non-focusable user controls.

Problem: When the user clicks Start (thereby giving it focus), then it hides and Reset appears, the Reset button automatically seems to get the focus. This isn't awful since key press events are still raised, but the focus causes a big problem. If the user presses Space, then the button interprets it as a Click event.

If I add a handler for KeyUp and KeyDown to the button itself and set the event to Handled, it will swallow the event if I hold down the space and let go, but not if I just tap it.

Question: How can I prevent Space from activating a button, while still being able to respond to the Space in my app?

A: 

Consider creating a simple custom control, or using one that you can set IsHitTestVisible="True" on. Then, place it somewhere within the same Grid, and hook up to its key events and other input events you'd like to capture.

To make sure that focus goes to your "invisible" control, you can call (yourControlsNameHere).Focus() once the Start button is pressed.

You could work with the visual/tab order to either put your hidden, focus-capturing control before or after the Reset button. I don't think your users would mind the idea that tabbing around the app could have them put the focus on the non-focusable user controls that their input correlates to.

Jeff Wilcox
Thanks! This is what I did. The only side effect was that I didn't seem to be able to consume the Space bar since Windows uses it to create a Click event. To get around that, I just wired up to the click event handler. For simplicity, I created a standard button with zero-sized borders and a 1x1 size after my Reset button in the tab order. Because of the space bar/click event weirdness, you can't hold down the space bar to receive multiple events (easily anyway), but in my application that wasn't too bad.Thanks so much for your response!
Arian Kulp
A: 

You can set the IsTabStop property of both buttons to false (e.g. when the Start button is pressed). This way it will be impossible for them to acquire focus, and will never handle keyboard events.

http://msdn.microsoft.com/en-us/library/system.windows.controls.control.istabstop%28VS.95%29.aspx

Stefan