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

2

7

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;
}
Alphabetical answered 22/10, 2009 at 14:59 Comment(0)
A
7

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;
Alphabetical answered 23/10, 2009 at 8:47 Comment(0)
M
1

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.

Melia answered 22/10, 2009 at 15:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.