C#:如何通过窗体及其控件拖动窗体?

7

我使用以下代码来拖动一个无边框窗体,通过点击和拖动窗体本身。它可以工作,但是当你点击并拖动位于窗体上的控件时却不起作用。我需要能够在单击某些控件但不是其他控件时拖动它 - 拖动标签,但不是按钮和文本框。我该怎么做?

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;
}
2个回答

7

实际上,我在这里找到了解决方案。

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

它有效。

另外,在我上面的代码中,如果需要调整大小,if语句应该更改为

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

1
使用Spy++分析哪些控件正在接收哪些Windows消息,然后您就会知道需要捕获什么。
没有深入查看您的代码,我想象主窗口上的子控件正在接收消息,而不是表单,您希望对其中一些进行特定响应。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接