A simple Class for Moving Controls At Runtime

2:02 AM
Here Is The Class:

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

namespace MoveControl
{
   sealed class clsMoveControl
    {
        public enum Direction
        {
            Any,
            Horizontal,
            Vertical
        }

        public static void StartMoving(Control cntrl)
        {
            StartMoving(cntrl, Direction.Any);
        }

        public static void StartMoving(Control cntrl, Direction dir)
        {
            StartMoving(cntrl, cntrl, dir);
        }

        public static void StartMoving(Control cntrl, Control container, Direction dir)
        {
            bool Dragging = false;
            Point DragStart = Point.Empty;
            cntrl.MouseDown += delegate(object sender, MouseEventArgs e)
            {
                Dragging = true;
                DragStart = new Point(e.X, e.Y);
                cntrl.Capture = true;
            };
            cntrl.MouseUp += delegate(object sender, MouseEventArgs e)
            {
                Dragging = false;
                cntrl.Capture = false;
            };
            cntrl.MouseMove += delegate(object sender, MouseEventArgs e)
            {
                if (Dragging)
                {
                    if (dir != Direction.Vertical)
                        container.Left = Math.Max(0, e.X + container.Left - DragStart.X);
                    if (dir != Direction.Horizontal)
                        container.Top = Math.Max(0, e.Y + container.Top - DragStart.Y);
                }
            };
        }
    }
}



How to Use Example :

1. Create a simple project .
2. On the load event of the form write the following coding

clsMoveControl.StartMoving(this);

This will make the form movable by clicking anywhare on the form and dragging it.
The same can be done for other controls like:

clsMoveControl.StartMoving(Button1);
 clsMoveControl.StartMoving(Panel1);
 
See it Live:

0 comments:

Post a Comment