Is there a way to make a UserControl unfocussable?
EDIT:
So SetStyle(ControlStyles.Selectable, false)
is the way to go. But still there is diffe
A UserControl, or any Control, will not be able to receive focus if the CanFocus property returns false. If you look at the code in reflector it basically checks 3 properties and if any are false then it will be un-focusable.
Setting the first two to false and having a functioning control is pretty much a contradiction. If it's possible though for your control to be functional with IsEnabled being false then that should work.
You can get closer to what you want by setting TabStop to false. That'll prevent the control from getting focused when, for instance, a dialog-box above its owning form closes.
Yes, the SetStyle(ControlStyles.Selectable, false); works only if you are inheriting from a control.
It will not work, if you are inheriting from a user control.
To get around the problem, I added a panel to the user control and docked the panel to "Fill". Added rest of the controls to the panel instead of the user control. It worked!
Enabled = false, perhaps?
Besides ControlStyles.Selectable there is also a ControlStyles.ContainerControl - the documentation is rather sparse on this topic (If true, the control is a container-like control), but it somehow affects if the child controls get focus instead of the control itself.
EDIT:
I have just noticed another interesting fact. Viewing a UserControl in reflector shows that it forces setting the input focus in OnMouseDown. So overriding OnMouseDown without calling base.OnMouseDown(e) resolves the issue with no side-effects.
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnMouseDown(MouseEventArgs e)
{
if (!this.FocusInside())
{
this.FocusInternal();
}
base.OnMouseDown(e);
}
In your constructor after InitializeComponent()
you need to call SetStyle and set the ControlStyles.Selectable style to false
:
SetStyle(ControlStyles.Selectable, false);