1

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

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

2 回答 2

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

于 2011-09-06T06:30:42.533 回答
0

不要将 VerticalScrollBar 添加到面板。AutoScrollMinSize设置属性时,面板已经自行处理滚动:

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();
}
于 2011-09-16T14:30:11.657 回答