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.
Addition: Now that I understand more of the
Control
class, I understand that if you derive fromControl
you should not subscribe to its events, but use the On.. functions, likeOnEnter
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With