Click here to Skip to main content
Click here to Skip to main content

Draggable WinForms Controls

By , 8 Apr 2011
 
Sometimes, you need to make the control draggable during runtime. It can be a form with FormBorderStyle property set to None, or any other situation.
I want to propose a simple extension method that allows you to make this possible.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace DraggableControls
{
    public static class ControlExtension
    {
        // TKey is control to drag, TValue is a flag used while dragging
        private static Dictionary<Control, bool> draggables = 
                   new Dictionary<Control, bool>();
        private static System.Drawing.Size mouseOffset;
 
        /// <summary>
        /// Enabling/disabling dragging for control
        /// </summary>
        public static void Draggable(this Control control, bool Enable)
        {
            if (Enable)
            {
                // enable drag feature
                if (draggables.ContainsKey(control))
                {   // return if control is already draggable
                    return;
                }
                // 'false' - initial state is 'not dragging'
                draggables.Add(control, false);
 
                // assign required event handlersnnn
                control.MouseDown += new MouseEventHandler(control_MouseDown);
                control.MouseUp += new MouseEventHandler(control_MouseUp);
                control.MouseMove += new MouseEventHandler(control_MouseMove);
            }
            else
            {
                // disable drag feature
                if (!draggables.ContainsKey(control))
                {  // return if control is not draggable
                    return;
                }
                // remove event handlers
                control.MouseDown -= control_MouseDown;
                control.MouseUp -= control_MouseUp;
                control.MouseMove -= control_MouseMove;
                draggables.Remove(control);
            }
        }
        static void control_MouseDown(object sender, MouseEventArgs e)
        {
            mouseOffset = new System.Drawing.Size(e.Location);
            // turning on dragging
            draggables[(Control)sender] = true;
        }
        static void control_MouseUp(object sender, MouseEventArgs e)
        {
            // turning off dragging
            draggables[(Control)sender] = false;
        }
        static void control_MouseMove(object sender, MouseEventArgs e)
        {
            // only if dragging is turned on
            if (draggables[(Control)sender] == true)
            {
                // calculations of control's new position
                System.Drawing.Point newLocationOffset = e.Location - mouseOffset;
                ((Control)sender).Left += newLocationOffset.X;
                ((Control)sender).Top += newLocationOffset.Y;
            }
        }
    }
}
 
It's pretty simple to use this code. To make control draggable, you just need to write one line of code:
AnyControl.Draggable(true);
and to disable this feature:
AnyControl.Draggable(false);
For example, if your Form contains two checkboxes named checkBox_DragForm and checkBox_DragButton with CheckedChanged event handlers assigned, and button with name btnTest, you may use the following code to enable/disable drag feature on Form (represented by this) or/and button:
 
private void checkBox_DragForm_CheckedChanged(object sender, EventArgs e)
{
    this.Draggable(checkBox_DragForm.Checked);
}
private void checkBox_DragButton_CheckedChanged(object sender, EventArgs e)
{
    btnTest.Draggable(checkBox_DragButton.Checked);
}
 
The code sample is here (VS2010 solution).
Hope this would be helpful.

License

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

About the Author

InTRUEdeR
Software Developer DevelopEx
Ukraine Ukraine
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberHorseman270323 Jan '13 - 22:18 
Very nice.
Only one little thing. You should add an event handler for control.MouseLeave.
AnswerRe: My vote of 5memberInTRUEdeR23 Jan '13 - 23:55 
Thanks for comment, but no, I should not.
control.MouseLeave can only occur when we've already released a control.
Or I missing something?
GeneralMy vote of 5memberLeszekCode27025 Oct '12 - 21:24 
Simple and sexy solution.
GeneralMy vote of 5membertruongvu_12324 Jun '12 - 23:20 
good job. Thanks!
GeneralReason for my vote of 5 easy to usememberCalvinWang18 Dec '11 - 23:17 
Reason for my vote of 5
easy to use
GeneralReason for my vote of 5 Very nice. Thanksmemberzenwalker198518 Dec '11 - 23:15 
Reason for my vote of 5
Very nice. Thanks
GeneralReason for my vote of 5 Excellent!! thank you very much..it...memberjawed.ace27 Jun '11 - 23:01 
Reason for my vote of 5
Excellent!!
thank you very much..it was useful for me Smile | :)
GeneralReason for my vote of 5 Nice one..thanks!!memberjawed.ace25 Jun '11 - 21:23 
Reason for my vote of 5
Nice one..thanks!!
GeneralRe: thanks for your vote!memberInTRUEdeR26 Jun '11 - 4:02 
thanks for your vote!
Generalwow! I like itmemberzhanghaocol1 May '11 - 22:44 
wow! I like it
GeneralReason for my vote of 5 Nice and usefull snippetmemberDotNetMastermind12 Apr '11 - 0:15 
Reason for my vote of 5
Nice and usefull snippet
GeneralReason for my vote of 5 Simple, like it.memberKim Togo11 Apr '11 - 22:16 
Reason for my vote of 5
Simple, like it.
GeneralReason for my vote of 5 Cool! Wish I needed to use this some...memberIGood11 Apr '11 - 13:54 
Reason for my vote of 5
Cool!
Wish I needed to use this somewhere Smile | :)
GeneralMy vote 5 This was really nice.memberJAxelsson10 Apr '11 - 21:35 
My vote 5
This was really nice.
GeneralReason for my vote of 5 NicememberHiMik200310 Apr '11 - 20:57 
Reason for my vote of 5
Nice
GeneralReason for my vote of 5 Elegant and simple. Nice.memberChris Trelawny-Ross8 Apr '11 - 7:32 
Reason for my vote of 5
Elegant and simple. Nice.

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 8 Apr 2011
Article Copyright 2011 by InTRUEdeR
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid