Click here to Skip to main content
15,881,559 members
Articles / Programming Languages / C#
Tip/Trick

Ultimate solution for moving a form by clicking anywhere in the window

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
26 Nov 2010CPOL3 min read 19.1K   15   5
Ultimate solution for moving a form by clicking anywhere in the window

Introduction

Normally a window is moved by clicking on the caption bar and dragging. Occasionally, people want to move borderless forms, or, move a form by clicking anywhere in the form without the limitation to the caption bar. There are many ways to do it. Two most commonly seen solutions are:

  1. Handle the mousedown, mouseup, mousemove events. You can mark a flag of drag in mousedown, record the initial mouse coordinates as the start point. In mousemove event, calculate the delta between the current mouse position and the start point. Set the window's new location using this delta as deviation value. Then the window will follow the mouse movement. And finally, set the drag flag to false to turn off the dragging.

    It's working. But you need to handle three events and use flags and variables to accomplish the work.

  2. A simpler way is to intercept the message loop of a form and retarget the mouse events hitting the client area to the caption bar, as shown in the following code snippet:
    C++
    private const int WM_NCHITTEST = 0x0084;
    private const int HTCLIENT = 1;
    private const int HTCAPTION = 2;
    protected override void WndProc(ref Message m)
    {
      base.WndProc(ref m);
      switch (m.Msg)
      {
        case WM_NCHITTEST:
          if (m.Result == (IntPtr)HTCLIENT)
          {
            m.Result = (IntPtr)HTCAPTION;
          }
          break;
      }
    }

If we have 20 forms and if we want them to have the similar behaviour, "copy & paste" the above codes into each one of the 20 files would be nasty. A clean way is to create a derived class from Windows.Form:

C#
public class InterceptProcForm:Form

and put the above codes in this class. Then you replace the default base class Form with InterceptProcForm for all your forms:

C#
public partial class Form1 : InterceptProcForm 

No more changes in your codes, all the forms are following your mouse now.

However, "ultimate" ends here would be too cheap. The question comes from "what if a form is completely covered by a user control?" Now the message in WndProc() originated from controls will be redirected to the controls' caption which is meaningless to a control and the form will stay there quietly.

The solution is to handle the mousemove event and flood it to its owner form, as shown in this link "C# borderless form move by usercontrol".

Once again we need to take reuse into consideration. In the above link, a generic type FormDragPanel is used and user panels can inherit from it to move the underlying form. It's an improvement but not enough. There are tens if not tons of various types of user control, for some of them we may want the dragging capability and for others we would just keep them as it is. A common type derived from UserControl is not feasible because C# disabled multiple inheritance. A quick thought is to create a separate FormDrag*** for each type of control: FormDragzLabel, FormDragPictureBox, FormDragProgressBar, etc. But your work does not end here. You need to touch the Designer generated code and add event chain in your form for each of the controls.

Inspired by Marcel, a kind of adaptor pattern is adopted to resolve the scenario. Simply add the following class FormDragBase in your project.

C#
public class FormDragBase : System.Windows.Forms.Form
    {
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;
        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage
		(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();
        protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                if (WindowState == FormWindowState.Normal)
                {
                    ReleaseCapture();
                    SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
                }
            }
        }
        public void AddDraggingControl(System.Windows.Forms.Control theControl)
        {
            theControl.MouseMove += 
		new System.Windows.Forms.MouseEventHandler(OnControlMouseMove);
        }
        private void OnControlMouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                if (WindowState == FormWindowState.Normal)
                {
                    ReleaseCapture();
                    SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
                }
            }
        }
    }

Derive your own form from this base class, then add the controls for which you want them to be transferable.

C#
public partial class Form1 : FormDragBase
    {
        public Form1()
        {
            InitializeComponent();
            AddDraggingControl(this.label1);
            AddDraggingControl(this.pictureBox1);
            AddDraggingControl(this.progressBar1);
        }
    }

Here you go. Simple and easy!

License

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


Written By
Team Leader
Canada Canada
Looking for something to do in the new year.

Comments and Discussions

 
GeneralNot C++ Pin
Ajay Vijayvargiya26-Nov-10 21:30
Ajay Vijayvargiya26-Nov-10 21:30 
GeneralRe: Not C++ Pin
enhzflep26-Nov-10 22:20
enhzflep26-Nov-10 22:20 
GeneralRe: Not C++ Pin
Ajay Vijayvargiya26-Nov-10 22:22
Ajay Vijayvargiya26-Nov-10 22:22 
GeneralRe: Not C++ Pin
Emilio Garavaglia27-Nov-10 6:59
Emilio Garavaglia27-Nov-10 6:59 
GeneralRe: Not C++ Pin
Ankur\m/30-Nov-10 23:00
professionalAnkur\m/30-Nov-10 23:00 

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

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