What the...?

Something bad happened

We're not sure what, but we have a few guesses.

Problem: Object reference not set to an instance of an object.
Ticket: 7864823
Server: Web01
Move controls on a form at runtime - CodeProject Click here to Skip to main content
11,715,043 members (66,349 online)
Click here to Skip to main content

Move controls on a form at runtime

, 17 Dec 2008 CPOL 2.3M 12.1K 116
Rate this:
Please Sign up or sign in to vote.
Move controls on a form at runtime by just using a helper class and one line of code.

Introduction

In some cases, it is handy to move controls on a form around by using your mouse. In this project, there is a helper class which does all the stuff needed to do this. Not only can a control be moved, but also its container.

Only one line of code is used to make a control movable (not ugly drag and drop):

Helper.ControlMover.Init(this.button1);

Really? Yes!!

Background

This code uses anonymous delegates to do the hard work. One advantage of this is that the helper class ControlMover has only static methods.

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

namespace Helper
{
  class ControlMover
  {
    public enum Direction
    {
      Any,
      Horizontal,
      Vertical
    }

    public static void Init(Control control)
    {
      Init(control, Direction.Any);
    }

    public static void Init(Control control, Direction direction)
    {
      Init(control, control, direction);
    }

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

Using the Code

An example how to use this code is presented in the project source file. All controls can be moved by a mouse. Also, a simple splitter using a toolbar is presented. Another panel containing a toolbar can be moved by using its toolbar.

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

namespace MoveYourControls
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();

      // Make your controls movable by a mouseclick
      Helper.ControlMover.Init(this.button1);
      Helper.ControlMover.Init(this.checkBox1);
      Helper.ControlMover.Init(this.groupBox1);
      Helper.ControlMover.Init(this.textBox1);
      Helper.ControlMover.Init(this.label1);

      // Move a panel by its toolstrip
      Helper.ControlMover.Init(this.toolStrip2, this.panel3, 
                               Helper.ControlMover.Direction.Any);

      // Make a splitter from toolstrip
      Helper.ControlMover.Init(this.toolStrip1, Helper.ControlMover.Direction.Vertical);
      this.toolStrip1.LocationChanged += delegate(object sender, EventArgs e)
      {
        this.panel1.Height = this.toolStrip1.Top;
      };
    }
  }
}

The Form after moving all the controls around.

Points of Interest

Sometimes, a control may only be moved in one direction. This is true for splitters and stuff. The helper class has a direction enumerator which makes things really easy:

Helper.ControlMover.Init(this.button1);
Helper.ControlMover.Init(this.button2, Helper.ControlMover.Direction.Any);
Helper.ControlMover.Init(this.button3, Helper.ControlMover.Direction.Horizontal);
Helper.ControlMover.Init(this.button4, Helper.ControlMover.Direction.Vertical);

Have fun!!

History

As of publication, version 1.0.0.0 is presented.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Alphons van der Heijden
Retired Van der Heijden Holding BV
Netherlands Netherlands
I'm Alphons van der Heijden, living in Lelystad, Netherlands, Europa, Earth. And currently I'm retiring from hard working ( ;- ), owning my own company. Because I'm full of energy, and a little to young to relax ...., I don't sit down, but create and recreate software solutions, that I like. Reinventing the wheel is my second nature. My interest is in the area of Internet technologies, .NET etc. I was there in 1992 when Mosaic came out, and from that point, my life changed dramatically, and so did the world, in fact. (Y)

You may also be interested in...

Comments and Discussions

 
Questionselect Multiple controls Pin
sameertm27-Aug-15 21:09
membersameertm27-Aug-15 21:09 
QuestionThanks. Pin
Member 1184133515-Jul-15 23:25
memberMember 1184133515-Jul-15 23:25 
QuestionI want to make the movable item: Menustrip, to dock automatically to a side, when moving it Pin
Member 1165490711-Jun-15 23:43
memberMember 1165490711-Jun-15 23:43 
QuestionDragging onto different panels? Pin
chriswarr676712-Apr-15 13:50
memberchriswarr676712-Apr-15 13:50 
Questionthank you Pin
Member 1063275217-Feb-15 0:51
memberMember 1063275217-Feb-15 0:51 
QuestionGreat .. until you drag into the scroll zone Pin
simonB201022-Dec-14 8:43
membersimonB201022-Dec-14 8:43 
GeneralMy vote of 5 Pin
swatipujari258-Nov-14 1:24
memberswatipujari258-Nov-14 1:24 
Questionadding a button Pin
Member 1088634415-Jun-14 18:45
memberMember 1088634415-Jun-14 18:45 
AnswerRe: adding a button Pin
Alphons van der Heijden8-Nov-14 11:28
professionalAlphons van der Heijden8-Nov-14 11:28 
GeneralPerfect my friend!! What I needed! Pin
Angelos_Alexopoulos13-Jun-14 2:23
memberAngelos_Alexopoulos13-Jun-14 2:23 
Suggestionnew article on base of your article Pin
zomorrod.company8-Feb-14 23:26
professionalzomorrod.company8-Feb-14 23:26 
GeneralThe Best Pin
spaceman8129-Jan-14 7:19
memberspaceman8129-Jan-14 7:19 
GeneralRe: The Best Pin
Alphons van der Heijden29-May-14 22:23
professionalAlphons van der Heijden29-May-14 22:23 
QuestionAdd arrow keys Pin
t_nedelchev8-Oct-13 21:48
membert_nedelchev8-Oct-13 21:48 
AnswerRe: Add arrow keys Pin
Alphons van der Heijden9-Oct-13 6:31
memberAlphons van der Heijden9-Oct-13 6:31 
GeneralRe: Add arrow keys Pin
t_nedelchev9-Oct-13 20:35
membert_nedelchev9-Oct-13 20:35 
GeneralRe: Add arrow keys Pin
spaceman8129-Jan-14 7:13
memberspaceman8129-Jan-14 7:13 
GeneralRe: Add arrow keys Pin
Alphons van der Heijden29-May-14 22:23
professionalAlphons van der Heijden29-May-14 22:23 
QuestionMoving the control in Java Pin
SharmaShruthi28-Aug-13 1:22
memberSharmaShruthi28-Aug-13 1:22 
AnswerRe: Moving the control in Java Pin
Alphons van der Heijden30-Aug-13 2:25
memberAlphons van der Heijden30-Aug-13 2:25 
GeneralMy vote of 5 Pin
Member 1021971719-Aug-13 20:51
memberMember 1021971719-Aug-13 20:51 
GeneralRe: My vote of 5 Pin
Alphons van der Heijden30-Aug-13 2:25
memberAlphons van der Heijden30-Aug-13 2:25 
GeneralMy vote of 5 Pin
Jayanta Chatterjee19-Aug-13 4:57
memberJayanta Chatterjee19-Aug-13 4:57 
QuestionWhat about ListView? Pin
SergeyAndreyev7-May-13 7:45
memberSergeyAndreyev7-May-13 7:45 
GeneralMy vote of 5 Pin
lucianomalta1-May-13 11:03
memberlucianomalta1-May-13 11:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150901.1 | Last Updated 17 Dec 2008
Article Copyright 2008 by Alphons van der Heijden
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid