C# – in WinForms can control focus change “automatically”? if yes, can I somehow distinguish this from user triggered focus change

ccontrolsfocuswinforms

I am not fully sure about this, but I seem to be observing cases where focus shifts automatically from one control to another, even after I explicitly programmatically set the focus to control that I want to have focused. Maybe it has to do with the control in question being a panel, and it seems that WinForms is happier to have a textbox focused than a panel.

Well, first of all, can somebody provide expert insight on this matter? And also, if it is indeed possible for the focus to change without explicit order from me (whether user action or programmatic) is it possible to programmatically distinguish the resulting Leave and Enter events? That is, I would like to programmatically counteract Leave/Enter events not caused by myself, but I still want to allow the user to change focus normally as part of work with the GUI.

Best Answer

Yes, that can happen. It is probably a ContainerControl that's messing up your focus, Form is derived from it. A ContainerControl goes hunting for a control to focus when it gets an activation event. It likes nested child controls, it will definitely skip your Panel if it has any controls.

The logic involved in WF to handle focus is very complicated, most of all due to validation. You'd be best off by staying out of trouble and avoid ever giving a Panel the focus. It isn't designed to be a focusable control, it has no way to indicate focus to the user. This is enforced by it having the ControlStyles.Selectable style turned off and the TabStop property set to false so the user can never focus it by tabbing or clicking.

The Enter event won't help, the Panel gets Enter both when it gets the focus or when one of its child controls get the focus. Either by the user tabbing or when you use the Focus() method. You'd have to wait until all focus events are done firing, something you can do with Control.BeginInvoke() or a Timer.

Well, I'm sure that doesn't help much but your problem description is fuzzy. Best way to proceed is to post a sample project that exhibits this behavior to a file sharing service or, as indicated, avoid ever trying to give a parent control the focus.

Related Topic