If I want to write a custom control, what's the difference between inheriting
from Control and UserControl?
How do I decide which of the two I should derive from?
Brian Pepin replies:
Main difference is not the "UserControl" part of the class, but the fact that
UserControl derives from ContainerControl.
ContainerControl has the additional logic to know how to navigate among children
using the keyboard. It has the notion of an "active" control within itself, and it
supports mnemonics and tabbing. Control doesn't do that, so if you want to compose
a control containing multiple child controls, ContainerControl must be the class to
derive from. UserControl is just a glossy layer on top of that.
The non-obvious part about this is that any container control can correctly
navigate among children, so if you put a bunch of child controls on a Control class
and slap it on a form, it will appear to work just fine. Until you place it in IE
or some other place where there is no parenting "Form" to do the keyboard navigation.
Then it will all break unless you are deriving from ContainerControl (and remember,
UserControl derives from ContainerControl).
If you put child controls on Control you are responsible for handling all keyboard
Boulter, as usual, provides an excellent summary:
The ContainerControl (which UserControl and Form derive
from) adds behavior that Control does not have, for example, keyboard handling (mnemonic
and tabs in particular). Also UserControl adds a composition based design experience.
This is what UserControl is all about.
You use Control if you are building a control that draws its content by overriding
the paint event.
You use UserControl if you are building a control that is composed of other controls.