views:

94

answers:

2

I have a form that I want to know which control on it has focus.

How can I do this? Best solution I have seen has me iterating all the controls on the screen. While doable, it seems like a lot of work just to know which control has the focus.

+2  A: 

It looks like THIS is the way to go on CF.

thelost
+1  A: 

You can either do what thelost said, or you can implement your own form base class to handle the task for you.

public class BaseForm : Form
{
    public BaseForm() 
    {
        this.Load += new EventHandler(BaseForm_Load);
    }

    void BaseForm_Load(object sender, EventArgs e)
    {
        this.HandleFocusTracking(this.Controls);
    }

    private void HandleFocusTracking(ControlCollection controlCollection)
    {
        foreach (Control control in controlCollection)
        {
            control.GotFocus += new EventHandler(control_GotFocus);
            this.HandleFocusTracking(control.Controls);
        }
    }

    void control_GotFocus(object sender, EventArgs e)
    {
        _activeControl = sender as Control;
    }

    public virtual Control ActiveControl
    {
        get { return _activeControl; }
    }
    private Control _activeControl;

}

It is impossible to avoid a control iteration, but if you did it this way the iteration will only happen once instead of every time you want to know the active control. You can then can just call the ActiveControl as per a standard winforms app as follows:

Control active = this.ActiveControl;

The only disadvantage with this is that if you had the requirement to add the new controls at runtime, then you'd have to ensure they were properly hooked up to the control_GotFocus event.

GenericTypeTea
While it looks nice, this does not work. This is because the LostFocus event comes before the GotFocus of the next control. So, in the LostFocus event you cannot know where the focus is (using this method. This method however, works fine:http://stackoverflow.com/questions/1648596/c-net-compact-framework-custom-usercontrol-focus-issue/1648653#1648653)
Vaccano
That's a bit harsh. It works fine, just not from the the LostFocus event. I can't think of a scenario whereby you'd want to know the next focused control on the LostFocus event anyway.
GenericTypeTea
@GenericTypeTea - I did not mean to be harsh at all. Sorry. I am very grateful for this response and the time you put into it. As to why I would want to know the next control... I felt I had a good reason. Thank you for your efforts. (As an added thanks, I gave a few upvotes to some of your better questions and answers.)
Vaccano
@Vaccano - I wasn't taking it personally. By harsh I meant that by saying "this doesn't work" infers that it doesn't work at all. Happy to help.
GenericTypeTea