Question:
There are problems with the FlowLayoutPanel
element in the program. I have a UserControlPanel
– and so I endlessly add this element in a separate thread to this FlowLayoutPanel
.
UserControlPanel panel = new UserControlPanel(a, spisok);
flowLayoutPanel1.Controls.Add(panel);
flowLayoutPanel1.Controls.SetChildIndex(panel, 0);
I insert each new UserControlPanel
at the beginning of the FlowLayoutPanel
, and the rest of the UserControlPanel
are shifted to the right and if everything is filled horizontally, they are rearranged to a new line. And if the FlowLayoutPanel
vertical is filled, it has a scroll.
Those. everything works as it should.
But the problem is this:
So let's imagine that the scroll is at the very top or in the middle. And if the application is not in the active window, and I access it by clicking in any area of the FlowLayoutPanel
, the scroll flies down and I have to turn it up every time to see what is added there at the beginning.
How is this treated?
UPDATE: Added sample project https://yadi.sk/d/SOkWH3xL3Qczeh
Every 3 seconds, a UserConrol
is added to the FLP
, when the FLP
is filled vertically, a scroll appears and if you hide any Conrol
by special. button, the scroll flies down, but does not stay in place, and the same thing happens when I click on the form if it is inactive.
Answer:
For the convenience of adding new elements to the FlowLayoutPanel
, we subscribe to the Control.ControlAdded
event with the following handler:
flowLayoutPanel1_ControlAdded(object sender, ControlEventArgs e)
{
var flp = (FlowLayoutPanel)sender;
flp.Controls.SetChildIndex(e.Control, 0);
flp.ScrollControlIntoView(e.Control);
}
Unlike the Control.Select()
and Control.Focus()
methods, which switch the focus to the selected control and prevent working with other controls on the same form, the ScrollableControl.ScrollControlIntoView(Control)
method does not intercept the focus, but only shifts the scroll like this, so that the child element passed in the parameter is in the visible area. Therefore, you can, for example, safely type in the TextBox
while adding new elements.
This handler will return the scroll to the topmost position to make the added element visible. Between additions, you can twist it as you like, although if elements are added often, then little will come of it, but you can pull it to check.