您可以通过在 (0, 0) 处添加然后将面板的显示区域向下和向右移动来模拟在左上区域添加按钮。
不要将按钮的位置设为 (-20, -20),而是设为 (0, 0)。
接下来,遍历面板中的所有其他控件,并将它们分别向右移动 20 像素和向下移动 20 像素。
最后,向下和向右滚动面板。
private void Form1_Load(object sender, EventArgs e)
{
btnResetPosition_Click(sender, e);
}
private void btnMoveToUpperLeft_Click(object sender, EventArgs e)
{
//Set Panel View to upper-left before moving around buttons
panel1.VerticalScroll.Value = panel1.VerticalScroll.Value = panel1.VerticalScroll.Minimum;
panel1.HorizontalScroll.Value = panel1.HorizontalScroll.Value = panel1.HorizontalScroll.Minimum;
//Move button1 to "upper-left"
button1.Location = new Point(0, 0);
//Adjust "static" controls right and down to simulate moving button1
button2.Location = new Point(button2.Location.X + 200, button2.Location.Y + 200);
button3.Location = new Point(button3.Location.X + 200, button3.Location.Y + 200);
//Scroll to show "static" controls in panel
panel1.VerticalScroll.Value = panel1.VerticalScroll.Value = panel1.VerticalScroll.Maximum;
panel1.HorizontalScroll.Value = panel1.HorizontalScroll.Value = panel1.HorizontalScroll.Maximum;
}
private void btnResetPosition_Click(object sender, EventArgs e)
{
//Set Panel View to upper-left before moving around buttons
panel1.VerticalScroll.Value = panel1.VerticalScroll.Value = panel1.VerticalScroll.Minimum;
panel1.HorizontalScroll.Value = panel1.HorizontalScroll.Value = panel1.HorizontalScroll.Minimum;
//Line up all three buttons
button1.Location = new Point(19, 17); // 19 and 17 are used so that when panel scrollbars appear, "static" controls appear to stay in the same place
button2.Location = button1.Location;
button2.Location = new Point(button1.Location.X, button1.Location.Y + 29);
button3.Location = button2.Location;
button3.Location = new Point(button2.Location.X, button2.Location.Y + 29);
}
要运行示例代码,请将“panel1”添加到名为“Form1”的表单中。将 panel1 的大小更改为 (111, 115)。将三个按钮添加到 panel1,名为“button1”、“button2”和“button3”。将两个按钮添加到名为“btnMoveToUpperLeft”和“btnResetPosition”的表单中。将示例代码粘贴到 Form1.cs 中。
请注意,用于移动滚动条的代码看起来很有趣,因为一个错误是,将滚动条设置为等于该值会导致滚动条不更新。 (How to scroll a panel manually?)