1. 创建FlowLayoutPanel控件
注意请把AutoScroll设置为true。
FlowLayoutPanel flpPanel= new System.Windows.Forms.FlowLayoutPanel();
flpPanel.AutoScroll = true;
flpPanel.Dock = System.Windows.Forms.DockStyle.Fill;
flpPanel.Location = new System.Drawing.Point(0, 0);
flpPanel.Name = "flpPanel";
flpPanel.Size = new System.Drawing.Size(252, 61);
flpPanel.TabIndex = 1;
2. 往FlowLayoutPanel动态创建控件
往FlowLayoutPanel动态创建100个Button,只要能实现显示垂直滚动条即可。
int butonCount = 100;
for(var i=0 ; i < buttonCount ; i++)
{
var button = new Button();
button.Name = String.Contact("btn",i.ToString());
button.Text = button.Name;
flpPanel.Controls.Add(button);
}
// 调用第3点的类进行绑定MouseDown及MouseMove事件
new TouchScroll(flpPanel);
3. 为FlowLayoutPanel处理MouseDown及MouseMove事件
创建TouchScroll类,当上述第2步往FlowLayoutPanel增加控件后可进行绑定。
注意:如FlowLayoutPanel子控件为自定义控件,请注意对AssignEvent里面的foreach中的Control进行处理
public class TouchScroll
{
private Point mouseDownPoint;
private FlowLayoutPanel parentPanel;
public TouchScroll(FlowLayoutPanel panel)
{
this.parentPanel = panel;
AssignEvent(this.parentPanel);
}
private void AssignEvent(Control control)
{
control.MouseDown += MouseDown;
control.MouseMove += MouseMove;
foreach (Control child in control.Controls)
{
AssignEvent(child);
}
}
private void MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
Point pointDifference = new Point(Cursor.Position.X + this.mouseDownPoint.X, Cursor.Position.Y - this.mouseDownPoint.Y);
if ((this.mouseDownPoint.X == Cursor.Position.X) && (this.mouseDownPoint.Y == Cursor.Position.Y))
return;
Point current = this.parentPanel.AutoScrollPosition;
this.parentPanel.AutoScrollPosition = new Point(Math.Abs(current.X) - pointDifference.X, Math.Abs(current.Y) - pointDifference.Y);
this.mouseDownPoint = Cursor.Position;
}
private void MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
this.mouseDownPoint = Cursor.Position;
}
}
4. 总结
此处主要使用MouseDown及Mouse事件处理FlowLayoutPanel的AutoScrollPosition。

本文介绍了如何在C#的Winform应用程序中,利用FlowLayoutPanel控件配合触摸屏实现内容的上下滚动。关键步骤包括设置FlowLayoutPanel的AutoScroll属性为true,动态添加控件,以及处理MouseDown和MouseMove事件来调整滚动位置。
264

被折叠的 条评论
为什么被折叠?



