Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to suppress UserControl to give focus the first child-control?

I have a UserControl which can have childcontrol.

The usercontrol have the styles:

this.SetStyle(
            ControlStyles.AllPaintingInWmPaint |
            ControlStyles.OptimizedDoubleBuffer |
            ControlStyles.Selectable |
            ControlStyles.SupportsTransparentBackColor |
            ControlStyles.UserPaint,
            true);

Now if I click on the usercontrol (not an child-control) i want the usercontrol to keep the focus, but the focus automatically goes to the first child-control. The same thing happens if i use the tab key.

i already tried to override OnGotFocus without success.

Any idea?

like image 636
Wowa Avatar asked Jan 24 '26 05:01

Wowa


1 Answers

This is hard-coded behavior inside the UserControl class, it traps the WM_SETFOCUS message and passes the focus to a child control. I do not know of a way to override this, even trapping it in WndProc() doesn't work since there is no good way to get the UC base class to handle it.

The best approach is to avoid the battle and use a docked Panel control to be the stand-in for focusing events you want the UC to handle. That requires some hacking as well, Panel is also a container control, but that can be bypassed. Check out my answer here for a focusable panel.

like image 84
Hans Passant Avatar answered Jan 25 '26 20:01

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!