开发者

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

开发者 https://www.devze.com 2022-12-09 08:22 出处:网络
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

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;
   开发者_如何学JAVA const int HTCLIENT = 0x1;
    const int HTCAPTION = 0x2;

    if (m.Msg == WM_NCHITTEST && (int)m.Result == HTCLIENT)
        m.Result = (IntPtr)HTCAPTION;
}


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;


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消