C#:如何从由窗体和控件拖动?(C#: How to drag a from by the form

2019-08-31 11:28发布

我用下面的代码将一个无国界的形式,通过点击和拖动窗体本身。 它的工作原理,但它不确实的,当你单击并拖动位于窗体上的控件。 我需要能够拖动它的一些控制,但不是别人的点击时 - 通过拖动标签,而是由按钮和文本框没有。 我该怎么做?

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

Answer 1:

其实,我找到了解决办法在这里 。

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;


Answer 2:

使用间谍++来分析控件接受​​什么Windows消息,你就会知道,然后你必须捕捉什么。

如果没有你的代码深深地看着我想象的子控件在主窗口中收到消息,而不是形式,你想对其中的一些具体回应。



文章来源: C#: How to drag a from by the form and its controls?