tags:

views:

224

answers:

4

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.

A: 

Enabled = false, perhaps?

Fredrik Mörk
Focus is disabled ... But there are side effects like different behaviour of background images ... So nice try .. :)
Matze
+2  A: 

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.

JaredPar
Much easier to just set the ControlStyles.Selectable style to false.
Jeff Yates
+3  A: 

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

SetStyle(ControlStyles.Selectable, false);
Adam Robinson
It does not work in case when UserControl has embedded TextBox. Text box will capture focus.
volody
@volody: Yes, the child control can capture focus, but the `UserControl` cannot.
Adam Robinson
A: 

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!

Ankit Mehta