flowLayoutPanel1设置内容随着鼠标滚动而滚动

当flowLayoutPanel1内容过多时,可以设置竖条,当时当鼠标滚动时,里面的内容不会随着鼠标的滚动而滚动,这就要求我们自己写事件了:

宗旨:判断鼠标是不是在flowLayoutPanel1区域内,如果在,设置flowLayoutPanel1的垂直滚动距离

给winform窗体加一个mousewheel监听事件

核心代码:

 private void Form1_MouseWheel(object sender, MouseEventArgs e)
        {
            //e.X e.Y以窗体左上角为原点,aPoint为鼠标滚动时的坐标
            Point aPoint = new Point(e.X,e.Y);

            //this.Location.X,this.Location.Y为窗体左上角相对于screen的坐标,得出的结果是鼠标相对于电脑screen的坐标
            aPoint.Offset(this.Location.X,this.Location.Y);
       
            Rectangle r = new Rectangle(flowLayoutPanel1.Location.X, flowLayoutPanel1.Location.Y, flowLayoutPanel1.Width, flowLayoutPanel1.Height);
            // MessageBox.Show(flowLayoutPanel1.Width+"  "+flowLayoutPanel1.Height);

            //判断鼠标是不是在flowLayoutPanel1区域内
            if (RectangleToScreen(r).Contains(aPoint))
            {
                //设置鼠标滚动幅度的大小
                flowLayoutPanel1.AutoScrollPosition = new Point(0,flowLayoutPanel1.VerticalScroll.Value-e.Delta/2);
            }

        }

往flowLayoutPannel1里面添加controls

  for (int i = 0; i < 100; i++)
            {
                Label l = new Label();
                l.Text = i.ToString();
                flowLayoutPanel1.Controls.Add(l);
                flowLayoutPanel1.ScrollControlIntoView(l);
                Application.DoEvents();
            }

完!!

原文地址:https://www.cnblogs.com/wwz-wwz/p/6770035.html