Alex Lizama

Alex Lizama

  • 0
  • 3
  • 83

Scrolling Problem Winform c# panel and button emulating swipe

Jun 7 2021 5:02 PM

Problem with Scrolling in WinForm C# in Panel AutoScroll with Dynamic created buttons. 
here is a simple example?


//form Form1.cs
//Created a Panel with Manual Designed Buttons and autoscrool= true. //You can click.down and scroll anywhere in panel1. it scrolls the way it //should. but if I create it Dynamic buttons(as coded) it does not work. I //click.down on buttons and i can not scroll????... I'm able to scroll if //clicked outside button... I need to click anywhere!!!! Please help


using System;
using System.Drawing;
using System.Windows.Forms;

namespace ScrollTouch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            new TouchScroll(panel1);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < 10; i++)
            {
                Button b = new Button();
                b.Text = i.ToString();      
                b.Size = new Size(100, 90);
                b.Location =  new Point(i*140, 0);
                panel1.Controls.Add(b);
            }

        }
    }
}


//form: TouchScroll.c (class)
using System;
using System.Drawing;
using System.Windows.Forms;

namespace ScrollTouch
{
    public class TouchScroll
    {

        private Point mouseDownPoint;
        private Panel parentPanel;

        public TouchScroll(Panel panel)
        {
            parentPanel = panel;
            AssignEvent(panel);

        }

        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 - mouseDownPoint.X, Cursor.Position.Y + mouseDownPoint.Y);
            if ((mouseDownPoint.X == Cursor.Position.X) && (mouseDownPoint.Y == Cursor.Position.Y))
                return;

            Point currAutos = parentPanel.AutoScrollPosition;
            parentPanel.AutoScrollPosition = new Point(Math.Abs(currAutos.X) + pointDifference.X, Math.Abs(currAutos.Y) + pointDifference.Y);
            mouseDownPoint = Cursor.Position;
        }

        private void MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                this.mouseDownPoint = Cursor.Position;
        }


    }
}


Answers (1)