I'm implementing a custom control that inherits from Control
. I want it to be focusable (it's a kind of list box).
In the constructor, I do
SetStyle(ControlStyles.Selectable, true);
I can now use Tab to navigate to the control.
However, when the control receives a mouse click, it does not automatically claim focus. I can work around this, of course:
protected override void OnMouseDown(MouseEventArgs e)
{
Focus();
base.OnMouseDown(e);
}
But this feels like a kludge that should not be necessary. Is this really the way to go? Or is there some way to tell Control
to claim focus automatically when it receives a mouse click?
Disassembly to the rescue! It turns out that
SetStyle(ControlStyles.UserMouse, true);
does the trick.
Ironically, I had read in the documentation:
UserMouse
: If true, the control does its own mouse processing, and mouse events are not handled by the operating system.
That seemed the exact opposite of what I wanted, so I had only tried setting it to false
... Way to go, WinForms documentation.
Yes, that what you should do. There are many controls that don't have a meaningful way to take the focus. PictureBox, Panel are good examples. Anything that derives from ContainerControl. Control.OnMouseDown() therefore doesn't automatically call Focus() in OnMouseDown().
Just overriding the OnMouseDown method isn't enough, you should also make it clear to the user that your control has the focus. So she'll have an idea where the keyboard strokes go. That requires overriding OnPaint() so you can draw a focus rectangle. ControlPaint.DrawFocusRectangle() is a boilerplate implementation for that.
But taking the focus is really only useful if you do something meaningful with keyboard messages. So you'll have to override OnKeyDown and/or OnKeyPressed as well. And show feedback to the user so she can see what she typed. If you don't have a useful implementation for that, you shouldn't take the focus. Which is why PictureBox doesn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With