表单没有 DragMove() 方法?

HoT*_*1CH 2 .net c# winforms

因此,无论单击什么元素,我都需要移动表单(我需要通过按住按钮拖动表单,表单是 100% 透明的),我尝试这样做:

 private void MessageForm_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            this.DragMove();
    }
Run Code Online (Sandbox Code Playgroud)

但我很惊讶,没有任何 DragMove()方法,它被重命名了或者我缺少什么?

如果这是不可能的,有没有其他方法可以做到这一点?

Cam*_*ker 6

你将需要这样的东西:

public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();

private void MessageForm_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{     
    if (e.Button == MouseButtons.Left)
    {
        ReleaseCapture();
        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
    }
}

private void button1_MouseDown(object sender, MouseEventArgs e) 
{
  if (e.Button == MouseButtons.Left) 
  {
    ReleaseCapture();
    SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
  }
}
Run Code Online (Sandbox Code Playgroud)

基本上,当您拖动窗口中的任何位置时,它的作用就像拖动标题栏/窗口标题一样。这对于无边框窗口非常有用。

编辑: 如果您使用按钮作为移动窗体的控件,则在附加单击事件处理程序时需要小心,因为您要覆盖该控件的 Windows 窗体事件循环。

通过将 ReleaseCapture 和 SendMessage 调用移动/添加到控件的 MouseDown 事件,您可以使用它来拖动窗口。只要将 MouseDown 事件更新为类似于上面的代码,任何控件都可以用于拖动窗口。