Knowing when a control has focus

Hi howzit

I have a panel which displays many different controls after certain user events...i.e. the controls are instantiated and displayed in runmode.

How do I know when one of these controls has focus   i.e. how can I create a Enter Event which relates to any control in this panel's collection, so that when a user clicks any of these run time controls, i can run code and get location and size information from this particular control

Regards,




Answer this question

Knowing when a control has focus

  • Sam Wane

    You can iterate to the control of the panel:


    public void WireFocusEvents(Control control)
    {
    foreach(Control innerControl in control.Controls)
    {
    innerControl.GotFocus += new EventHandler(innerControl_GotFocus);
    }
    }

    private void innerControl_GotFocus(object sender, EventArgs e)
    {
    Control control = (Control)sender;
    MessageBox.Show( "Control with name " + control.Name + " has got the focus." );
    }




  • smalljoe

    But in your code there are controls added to a Form, not a panel but i will take a look at it tonight when i am home.


  • Shiby

    Is read that you add the controls at runtime, then it is easy to wire the ControlAdded event of the panel and there wire the GotFocus event of the control that has been added:


    private void pnlPanel_ControlAdded(object sender, ControlEventArgs e)
    {
    Control control = (Control)sender;
    control.GotFocus += new EventHandler(control_GotFocus);
    }
    private void control_GotFocus(object sender, EventArgs e)
    {
    Control control = (Control)sender;
    MessageBox.Show( "Control with name " + control.Name + " has got the focus." );
    }



  • Christian Gram

    Hey PJ, once again thanks for all your help really appreciate it. Your code works perfectly under normal conditions...but because my application presents the user with a design mode in run mode that code doesn't work.

    Please refer to the email I sent you...which has all the code to prove to you.

    Thanks,
    David



  • MS440

    you can do a test:

    if myPanel.Controls.Contains(myForm.ActiveControl)

    rather than hook up with the Enter Events of the child controls of the panel. if the panel can have container controls, you can provide a recursive function that iterates on the inner child controls.



  • Knowing when a control has focus