Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make a UserControl unfocussable?

Tags:

.net

winforms

Is there a way to make a UserControl unfocussable?

EDIT: So SetStyle(ControlStyles.Selectable, false)

is the way to go. But still there is difference to Control. If you inherit form Control the initial control does not lose focus. But after clicking on your control that is derived from UserControl and

ControlStyles.Selectable

is applied focus is removed from initial control.

like image 489
Matze Avatar asked Apr 24 '09 12:04

Matze


2 Answers

In your constructor after InitializeComponent() you need to call SetStyle and set the ControlStyles.Selectable style to false:

SetStyle(ControlStyles.Selectable, false);
like image 57
Adam Robinson Avatar answered Nov 07 '22 06:11

Adam Robinson


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);
}
like image 35
tombam Avatar answered Nov 07 '22 05:11

tombam