Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to drag a from by the form and its controls?

I use the following code to drag a borderless form, by clicking and dragging the form itself. It works, but it doesn't for when you click and drag a control located on the form. I need to be able to drag it when clicked on some of the controls but not others - drag by labels, but don't by buttons and text boxes. How do I do it?

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    const int WM_NCHITTEST = 0x84;
    const int HTCLIENT = 0x1;
    const int HTCAPTION = 0x2;

    if (m.Msg == WM_NCHITTEST && (int)m.Result == HTCLIENT)
        m.Result = (IntPtr)HTCAPTION;
}
like image 619
flamey Avatar asked Oct 22 '09 14:10

flamey


2 Answers

Actually, I found the solution here.

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

// Paste the below code in the your label control MouseDown event
if (e.Button == MouseButtons.Left)
{
    ReleaseCapture();
    SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
}

it works.

Also, in my code above, if resizing is desired, if statement should be changed to

        if (m.Msg == WM_NCHITTEST)
            if ((int)m.Result == HTCLIENT)
                m.Result = (IntPtr)HTCAPTION;
like image 56
flamey Avatar answered Sep 28 '22 07:09

flamey


Use Spy++ to analyse what controls are receiving what Windows Messages, you'll then know what you need to be capturing.

Without looking deeply at your code I'm imagining that child controls on the main Window are receiving messages rather than the form and you want to respond to some of these specifically.

like image 43
Neil Kimber Avatar answered Sep 28 '22 08:09

Neil Kimber