Is there a way to make a UserControl unfocussable?

前端 未结 6 691
迷失自我
迷失自我 2021-01-04 11:43

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

相关标签:
6条回答
  • 2021-01-04 12:19

    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.

    • IsHandleCreated
    • IsVisible
    • IsEnabled

    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.

    0 讨论(0)
  • 2021-01-04 12:22

    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.

    0 讨论(0)
  • 2021-01-04 12:26

    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!

    0 讨论(0)
  • 2021-01-04 12:29

    Enabled = false, perhaps?

    0 讨论(0)
  • 2021-01-04 12:32

    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);
    }
    
    0 讨论(0)
  • 2021-01-04 12:36

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

    SetStyle(ControlStyles.Selectable, false);
    
    0 讨论(0)
提交回复
热议问题