6
votes

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?

1
Google says this might be a duplicate: stackoverflow.com/questions/30184/… - rie819
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
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 codeproject.com/Articles/55180/… - Matthew Layton
Does the window have a titlebar? - Blachshma
So the window should be moved by click-dragging from both the titlebar and the panel? - Blachshma

1 Answers

17
votes

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);
    }
}