6

I have a WinForms project. I have a panel on the top of my window. I want that panel to be able to move the window, when the user clicks on it and then drags.

How can I do this?

Victor
  • 13,914
  • 19
  • 78
  • 147
  • 1
    Google says this might be a duplicate: http://stackoverflow.com/questions/30184/winforms-click-drag-anywhere-in-the-form-to-move-it-as-if-clicked-in-the-form – rie819 Nov 20 '12 at 16:09
  • 2
    No! It is not. I don't want the user to be able to move the window anywhere in the form. I want the user to be able to move the window just from `panel1` control – Victor Nov 20 '12 at 16:10
  • 2
    Look up "Daniel Moth, Vista Glass" in google. I know his tutorial shows you a method which will allow you to do this (its a Win32 call). Also this might be of some interest http://www.codeproject.com/Articles/55180/Extending-the-Non-Client-Area-in-Aero – Matthew Layton Nov 20 '12 at 16:10
  • 1
    Does the window have a titlebar? – Blachshma Nov 20 '12 at 16:11
  • So the window should be moved by click-dragging from both the titlebar and the panel? – Blachshma Nov 20 '12 at 16:13

1 Answers1

19

Add the following declerations to your class:

public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HTCAPTION = 0x2;

[DllImport("User32.dll")]
public static extern bool ReleaseCapture();

[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

Put this in your panel's MouseDown event:

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        ReleaseCapture();
        SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
    }
}
Victor
  • 13,914
  • 19
  • 78
  • 147
Blachshma
  • 17,097
  • 4
  • 58
  • 72
  • 1
    Excellent! +1 avoids abstractions trying to mathematically figure out cursor positions, offsets, and so on.. but nope, instead this mans just runs directly into the building, gets the ice cream cones and taps into the windows messaging system. Nice! Thank you. – Leo Gurdian Feb 10 '16 at 13:08