Setting Focus to a .NET UserControl...?

Sambo picture Sambo · Mar 2, 2010 · Viewed 19.5k times · Source

I'm creating a custom control derived from UserControl that I would like to set focus to.

The custom control contains a ComboBox control and I draw some strings beside it.

The ComboBox can receive focus, but I would like to be able to set focus to the UserControl itself. My OnPaint handler is set up to draw the control slightly differently if it has focus but I call CanFocus() from the parent form when I create my custom control and it returns false.

Is there a property or something to set?

Answer

Hans Passant picture Hans Passant · Mar 2, 2010

UserControl will fight you tooth and nail to avoid getting the focus. It has code that automatically passes the focus to a child control (if any) if it does get the focus. You'll at a minimum have to override WndProc() and trap the WM_SETFOCUS message. There might be other surgery needed, like ControlStyles.Selectable and the TabStop and TabIndex properties.

Your next issue is that UserControl won't respond meaningfully to, say, keyboard messages when it does have focus. You'll need to detect clicks on the UC background to handle mouse messages, as well as override the painting so it is obvious to the user that the UC has the focus (use ControlPaint.DrawFocusRectangle). If this starts to sound unattractive, it's because UC was really meant to be a container control.