Panel AutoScrollPosition在元素之间留下空白区域

时间:2017-01-11 15:31:47

标签: c# winforms autoscroll

有人可以解释为什么下面的代码会在插入的元素之间留下空格以及如何修复它?

enter image description here

private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
    {
        if (outLine.Data != null && !String.IsNullOrWhiteSpace(outLine.Data))
        {
            this.lineCount++;
            Label TestLBL = new Label();
            TestLBL.Text = outLine.Data.TrimStart();
            TestLBL.Name = this.lineCount.ToString();
            TestLBL.AutoSize = true;
            TestLBL.Location = new Point(10, panel1.Controls.Count * 20);

            BeginInvoke(new MethodInvoker(() =>
            {
                panel1.Controls.Add(TestLBL);
                panel1.AutoScrollPosition = new Point(10, this.lineCount * 20);


            }));
        }
    }

1 个答案:

答案 0 :(得分:1)

由于您没有使用FlowLayoutPanel,您必须补偿滚动条位置才能获得正确的位置:

TestLBL.Location = new Point(10, panel1.AutoScrollPosition.Y + panel1.Controls.Count * 20);

您应该将所有GUI控件创建代码放在BeginInvoke块中。 GUI控件就像在GUI线程上创建一样。