Question

I have a WindowsForm application that has a FlowLayoutPanel container with a TextBox inside. This control is bigger than the flow panel, I've set the flow panel to AutoScroll = true.

The problem is I don't know how to make the flow panel scroll to the position of the text edition. If I write continuously in the textbox eventually I pass beyond of what it is visible. The scroll remains at the top and I can't see what it is written.

In consequence the question is, how can I make the container react to keep visible what it is being written?

Was it helpful?

Solution

I think I finally did it:

public partial class Form1 : Form
{
    public Point InitialTextBoxLoc ;

    public Form1()
    {
        InitializeComponent();
        InitialTextBoxLoc = textBox1.Location;
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        Point caretLocalLoc = textBox1.GetPositionFromCharIndex(textBox1.Text.Length-1);
        Point caretLoc = new Point(caretLocalLoc.X + InitialTextBoxLoc.X,
                                   caretLocalLoc.Y + InitialTextBoxLoc.Y);

        Point scrollLoc = flowLayoutPanel1.AutoScrollPosition;
        if (caretLoc.X >= flowLayoutPanel1.Size.Width-10)
        {
            scrollLoc.X = caretLoc.X;

        }

        if (caretLoc.Y >= flowLayoutPanel1.Size.Height-10)
        {
            scrollLoc.Y = caretLoc.Y;
        }

        flowLayoutPanel1.AutoScrollPosition = scrollLoc;

    }
}

OTHER TIPS

There is a hacky solution, but if there is nothing better you can try it. First, subscribe for a TextChanged event. Than, on text changed, check in which line is the caret, check what's the height of the line and scroll the flow layout panel to the position of the line.

The hacky bit is basically to get the height of the line. To do that you have to subtract Y coordinate of the second line from the Y coordinate of the first line.

So the code is:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    int lineHeight = 0;
    if (textBox1.Lines.Count() > 1)
    {
        Point p1 = textBox1.GetPositionFromCharIndex(textBox1.GetFirstCharIndexFromLine(0));
        Point p2 = textBox1.GetPositionFromCharIndex(textBox1.GetFirstCharIndexFromLine(1));
        lineHeight = Math.Abs(p1.Y - p2.Y);
    }

    int lineIndex = textBox1.GetLineFromCharIndex(textBox1.SelectionStart);
    flowLayoutPanel1.AutoScrollPosition = new Point(0, lineIndex * lineHeight);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top