C# Winform FlowLayoutPanel控件在触摸屏下实现内容上下翻

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值