Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set focus to a Usercontrol

I have 50 UserControls that I add to a flowlayoutPanel dynamically. I need to set focus to a user control but it doesn't work. I have been searching a lot but can't find any example that I understand.

The only example that I find is this Setting Focus to a .NET UserControl...?

I tried to use userCtrl.Focus(); but it didn't work. As I have been reading the usercontrol doesn't like to have focus.

like image 887
tony Avatar asked Sep 13 '16 13:09

tony


1 Answers

Addition: Now that I understand more of the Control class, I understand that if you derive from Control you should not subscribe to its events, but use the On.. functions, like OnEnter. I've changed my answer accordingly

To Activate any Control, including a UserControl use Control.Select().

If you do this for a TextBox, you'll see that Select ensures that it gets the input focus.

I guess you want to do something with the selected UserControl (the Control that has the focus), for instance, you want to change its appearance, or select any of the controls on it. To do this, your UserControl class has to subscribe to the events Control.Enter and Control.Leave

I have created a UserControl with a CheckBox that is automatically checked whenever the UserControl is selected (has the input focus):

Addition: If you derive from a Control, don't subscribe to events Enter and Leave. Instead override the functions that raise these events: OnEnter / OnLeave.

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    protected override void OnEnter(EventArgs e)
    {
        this.checkBox1.Checked = true;
        base.OnEnter(e); // this will raise the Enter event
    }

    protected override void OnLeave(EventArgs e)
    {
        this.checkBox1.Checked = false;
        base.OnLeave(e); // this will raise the Leave event
    }
}

I have a form with a button, and an event handler that is called when the button is clicked:

private void OnButton1Clicked(object sender, EventArgs e)
{
    this.userControl1.Select();
}

Now whenever the button is clicked I see that the user control gets the focus because the check box is checked and whenever I click elsewhere the checkbox is unchecked.

like image 158
Harald Coppoolse Avatar answered Sep 28 '22 12:09

Harald Coppoolse