在面板中滚动形状

时间:2011-09-06 05:20:33

标签: c# winforms vertical-scrolling

我正在开发一个在面板上绘制形状的程序。我在面板上添加了一个垂直滚动条,但在滚动面板时,形状保持不变,不滚动。如何使这些形状滚动?
我在绘图处理程序中使用此代码来更新这些形状:

e.Graphics.FillRectangle(Brushes.Red, selectedRect);

2 个答案:

答案 0 :(得分:0)

滚动时你应该注意面板的实际滚动位置,并在再次绘制形状时考虑这个偏移。

网上有这样的例子(不完全是你的情况,但可以帮助找出问题):

private int count; 
private ArrayList arrayctl = new ArrayList();

private void button1_Click(object sender, System.EventArgs e) 
{ 
    TextBox newtxt = new TextBox(); 
    newtxt.Text = count.ToString(); 
    count++; arrayctl.Add(newtxt); 
    DrawControls(); 
} 

private void DrawControls() 
{ 
    System.Drawing.Point CurrentPoint; CurrentPoint = panel1.AutoScrollPosition; 
    int i = 0; 
    panel1.Controls.Clear(); 
    panel1.SuspendLayout(); 
    foreach (TextBox txt in arrayctl) 
    {
     panel1.Controls.Add(txt); 
        txt.Width = panel1.ClientRectangle.Width; 
        txt.Top = i; i += txt.Height; 
    } 
    panel1.ResumeLayout(); 
    panel1.AutoScrollPosition = new Point(Math.Abs(panel1.AutoScrollPosition.X), Math.Abs(CurrentPoint.Y)); 
}

我也在SO:Control position inside Windows.Forms.Panel with autoscroll

中找到了这个

答案 1 :(得分:0)

不要将VerticalScrollBar添加到面板。当您设置AutoScrollMinSize属性时,Panel已经处理了自己的滚动:

Rectangle selectedRect = new Rectangle(16, 16, 64, 28);

private void Form1_Load(object sender, EventArgs e)
{
  panel1.AutoScrollMinSize = new Size(panel1.ClientRectangle.Width - SystemInformation.VerticalScrollBarWidth, 1200);
}

private void panel1_Paint(object sender, PaintEventArgs e)
{
  e.Graphics.TranslateTransform(panel1.AutoScrollPosition.X, panel1.AutoScrollPosition.Y);
  e.Graphics.FillRectangle(Brushes.Red, selectedRect);
}

private void panel1_Scroll(object sender, ScrollEventArgs e)
{
  panel1.Invalidate();
}