Any tips on debugging focus issues in WPF?
Specifically, I have a button that opens a non-modal child window. Something in the main window steals the focus 开发者_运维技巧away from the child window as it opens.
The fully general approach is to comment out parts of code until the problem goes away. I'm looking for faster methods.
I'm using Snoop to do this right now.
For starters, Snoop shows the current focused element and the current FocusScope in the status bar.
You can get it to show you all the GotFocus and LostFocus events:
- Run your app.
- Run Snoop.
- Choose your app in the dropdown.
- Click the binoculars ("Snoop") button.
- On the right pane, click the Events tab.
- Click to bring down the dropdown.
- Scroll down to the Keyboard section and check GotKeyboardFocus, LostKeyboardFocus, and optionally the PreviewXXX events.
- Now do what you need to do to manipulate focus and watch the Snoop window.
Similarly you can track the FocusManager events the same way.
I haven't tried this myself so can't tell exact steps, but you can try to use FocusManager.FocusedElement and FocusManager.GetFocusedElement Method to try and find the element stealing focus from your child window.
Other useful link -
Focus Overview(Have code for getting focused element): http://msdn.microsoft.com/en-us/library/aa969768.aspx#Focus_Events
You can try using a tool like UI Spy or Snoop to watch for the event that changes the focus. I haven't used these tools for this purpose, but I believe they can help you.
Could you please mention the main operations (without going into client specific business - if it is a client project) - like is there any events hooked on to the elements, Any other operation happening on the button click - Anything which happens for any element in the parent window after the child window is shown which steals the focus. Also check any related events hooked which happen during button click event.
These are some of the ways you can start your investigation.
I just read about some deadlock...hope this helps (search for control.leave in msdn.microwoft.com
Caution Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Doing so can cause your application or the operating system to stop responding. For more information, see the WM_KILLFOCUS topic in the "Keyboard Input Reference" section, and the "Message Deadlocks" section of the "About Messages and Message Queues" topic in the MSDN library at http://msdn.microsoft.com/library.
You can try to track calls to the System.Window.UIElement.Focus method (in the PresentationCore.dll) in the context of your application using Runtime Flow (developed by me).
精彩评论