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

Draggable Form: Drag a Borderless Form by Clicking Anywhere on the Form

By , 6 Apr 2006
 
Sample image

Introduction

This is useful when you have a form without any border and you want to allow the user to drag it. This is a simple code and doesn't require any explanation at all. But I feel this will be helpful for at least some of you for your development. If you set the BorderStyle of a form to None, no title bar will be available for you to move the form. Here you can make use of this simple code to setup a base form and inherit all your form from this base form. After inheriting from this base form, you will be provided with two more properties in the Property Editor, Draggable (boolean) and ExcludeList (String). By setting the Draggable property to true, you are enabling the draggable feature of the form. You can pass a comma separated list of controls for which you don't want the draggable feature to be enabled. That is by default if Draggable=true, the form will be draggable by clicking anywhere on the form and any controls on the form. And naturally, you don't want the form draggable while a user clicks on a Button on it. So you can pass the name of the button to this list. E.g.: ExcludeList = "button1, button2, button3";.

FormBase.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DraggableForm
{    
    public class FormBase :Form
    {
        #region Declarations
        private bool drag = false;
        private Point start_point = new Point(0, 0);
        private bool draggable = true;
        private string exclude_list = "";

        /// <SUMMARY>
        /// Required designer variable.
        /// </SUMMARY>
        private System.ComponentModel.IContainer components = null;
        #endregion

        #region Constructor , Dispose

        public FormBase()
        {
            InitializeComponent();

        //
        //Adding Mouse Event Handlers for the Form
        //
        this.MouseDown += new MouseEventHandler(Form_MouseDown);
            this.MouseUp += new MouseEventHandler(Form_MouseUp);
            this.MouseMove += new MouseEventHandler(Form_MouseMove);
        }     

        /// <SUMMARY>
        /// Clean up any resources being used.
        /// </SUMMARY>
        /// true if managed resources should be disposed; otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #endregion

        #region Windows Form Designer generated code

        /// <SUMMARY>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </SUMMARY>
        private void InitializeComponent()
        {
            // 
            // FormBase
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(369, 182);
            this.Name = "FormBase";
            this.Text = "AlerterForm";
        }

        #endregion

        #region Overriden Functions

        protected override void OnControlAdded(ControlEventArgs e)
        {
            //
            //Add Mouse Event Handlers for each control added into the form,
            //if Draggable property of the form is set to true and the control
            //name is not in the ExcludeList.Exclude list is the comma separated
            //list of the Controls for which you do not require the mouse handler 
            //to be added. For Example a button.  
            //
            if (this.Draggable && (this.ExcludeList.IndexOf(e.Control.Name) == -1))
            {
                e.Control.MouseDown += new MouseEventHandler(Form_MouseDown);
                e.Control.MouseUp += new MouseEventHandler(Form_MouseUp);
                e.Control.MouseMove += new MouseEventHandler(Form_MouseMove);
            }
            base.OnControlAdded(e);
        }

        #endregion

        #region Event Handlers

        void Form_MouseDown(object sender, MouseEventArgs e)
        {          
            //
            //On Mouse Down set the flag drag=true and 
            //Store the clicked point to the start_point variable
            //
            this.drag = true;            
            this.start_point = new Point(e.X, e.Y);
        }

        void Form_MouseUp(object sender, MouseEventArgs e)
        {
            //
            //Set the drag flag = false;
            //
            this.drag = false;
        }

        void Form_MouseMove(object sender, MouseEventArgs e)
        {
            //
            //If drag = true, drag the form
            //
            if (this.drag)
            {
                Point p1 = new Point(e.X, e.Y);
                Point p2 = this.PointToScreen(p1);
                Point p3 = new Point(p2.X - this.start_point.X, 
                                     p2.Y - this.start_point.Y);
                this.Location = p3;
            }
        }

        #endregion

        #region Properties

        public string ExcludeList
        {
            set
            {
                this.exclude_list = value;
            }
            get
            {
                return this.exclude_list.Trim();
            }
        }

        public bool Draggable
        {
            set
            {
                this.draggable = value;
            }
            get
            {
                return this.draggable;
            }
        }

        #endregion
    }
}

Now, you can simply inherit your form from the FormBase and voila, it'll be draggable. If you have any suggestions, please mail me. I love to have friends and that's the reason I am here. Happy coding!

License

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

About the Author

Russell Aboobacker
Web Developer
India India
Member
Russell Aboobacker is a Software Engineer from India, Currently working in Cognizant, Bangalore as Software Architect. He Enjoys Coding and Sharing his Experiences with the Colleagues and Friends.When he is not coding he enjoys spending time with his Family.
 
If you have any suggestions / Ideas , Share it With me. arusselkm@yahoo.com

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   
Questiongreat jobmemberMustafa Magdy15 Jul '11 - 12:49 
hi, this is not working if the form is RightToLeft, any ideas???
GeneralGreat!!!memberDavidDiego29 Dec '10 - 21:25 
Hello,
 
It has just worked perfectly!
 
Thank you
 
David D.
GeneralRemove handles to movememberCFQüeb2 Apr '09 - 8:30 
If you want allow to end user decide if move or not a window, you can place a check box that modified the Draggable property.
 
 public bool Draggable
        {
            set
            {
                this.draggable = value;
                if (!Draggable)
                {
                    RemoveMoveHandlersFromBaseForm();
                    RemoveHandlesOnChildControls();
                }
                else
                {
                    AddMoveHandlersFromBaseForm();
                    AddHandlesOnChildControls();
                }
            }
            get
            {
                return this.draggable;
            }
        }
 
Check that events handlers has been moved into methods.
GeneralRemoving the handles to move the formmemberCFQüeb2 Apr '09 - 8:27 
You can allows to end user decide if a window can be moved with a check box available at runtime. this check box must to change the Draggable property and you must to remove the handlers:
 
public bool Draggable
{
set
{
this.draggable = value;
if (!Draggable)
{
RemoveMoveHandlersFromBaseForm();
RemoveHandlesOnChildControls();
}
else
{
AddMoveHandlersFromBaseForm();
AddHandlesOnChildControls();
}
}
get
{
return this.draggable;
}
} Laugh | :laugh:
QuestionHow to move or drag a borderless form in vb.netmemberThe Ricmann14 Aug '08 - 1:35 
I have seen many valid and good ideas, however I would say some to be difficult for the beginner. If you need an easy and simple way that you can remember then check out the link on www.pro2visual.com
GeneralVery good for widgets and resx questionmembermilkplus7 Sep '07 - 5:39 
Hello,
 
Thanks for an excellent article.
 
I used this class in my own article
http://www.codeproject.com/useritems/LoginTime.asp
 
I was going to write a widget using the Javascript system that Google desktop or Yahoo has but C# is so much more powerful. You can't get the username or save data with a Javascript widget. So I found your article as used it as a starting point. Thanks!!
 
Two questions for you:
- i've noticed copyright headers in other codeproject source files. what is your opinion about doing that?
- exactly how did you create a resx file under each form source file. I am only able to add an item to the project and then VS does all kinds of crazy stuff when I try to rename it and move it. it creates a source file with getters. Could you please explain your process?

GeneralTearing/Messy Paintingmemberxr280xr27 Aug '07 - 7:58 
When I have implemented this concept, I find that the window gets painted in many of the spots it was dragged across leaving a trail. Does that make sense? Is there a way to to prevent that?
GeneralThe Shortest WaymemberAnt Htoo Naing6 Jul '06 - 8:43 
protected override void WndProc(ref Message m)
{
if (m.Msg == 163 && this.ClientRectangle.Contains(this.PointToClient(new Point(m.LParam.ToInt32()))) && m.WParam.ToInt32() == 2)
m.WParam = (IntPtr)1;
 
base.WndProc(ref m);
 
if (m.Msg == 132 && m.Result.ToInt32() == 1)
m.Result = (IntPtr)2;
}
 

Enjoy Smile | :)
aNT---
GeneralThe Shortest Way (in VB.NET)memberAnt Htoo Naing6 Jul '06 - 8:52 
Protected Overrides Sub WndProc(ByRef m As Message)
If (((m.Msg = 163) And ClientRectangle.Contains(PointToClient(New Point(m.LParam.ToInt32)))) And (m.WParam.ToInt32 = 2)) Then
m.WParam = CType(1, IntPtr)
End If
MyBase.WndProc(m)
If ((m.Msg = 132) And (m.Result.ToInt32 = 1)) Then
m.Result = CType(2, IntPtr)
End If
End Sub
 
Enjoy Smile | :)
aNT---
GeneralRe: The Shortest Way (in VB.NET)memberkaushik25910628 Mar '07 - 20:33 
suuuuuuuuuuuuuuupppppppppppppeeeeeeeeeeerb...lots of thanxxxxxx

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 7 Apr 2006
Article Copyright 2006 by Russell Aboobacker
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid