views:

183

answers:

2

I can use the Control.Enter and Control.Leave events to detect when user focus enters or leaves a control, but this only works on a per-form basis. I use more than one form in my application, and want to track which control has user focus, I have to use the forms' Activated and Deactivated events to track which form is active and then track which control is focused within each form.

We're building a client using the DockPanel suite, so we don't have direct access to the controls' forms. We can't just add listeners to the control's top-level form because that changes when the user docks or undocks the panel. But we still need to track focus on a per-application basis. How do I detect control entering/leaving on a per-application basis, without access to the control's form?

A: 

Maybe check out the Unity Aplication Block and Inversion Of Control (IOC) Container Dependency Injections?

http://codebetter.com/blogs/david.hayden/archive/2008/02/22/unity-ioc-screencast.aspx

REA_ANDREW
+1  A: 

Could you hook into the Control.GotFocus/Control.LostFocus instead and then keep global track of which control currently has the focus?

Adding these event hooks to every control would be pretty tedious and error prone as you might miss a control of interest. So instead how about using Application.AddMessageFilter call in order to get a callback for each windows message that occurs in the application.

Then you can watch all the WM___SETFOCUS and WM_KILLFOCUS calls and keep a note of the current control with the focus. Remember to use the handy Control.FromHandle static method to get a nice .NET control reference from the window handle that you cache when tracking the two windows messages.

Phil Wright
Unfortunately the WM_SETFOCUS message doesn't always go through the message queue so I can't intercept it. See http://www.pcreview.co.uk/forums/thread-1314811.php
Simon