c# - 表单没有 DragMove() 方法?

标签 c# .net winforms

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

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

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

如果这是不可能的,还有其他方法吗?

最佳答案

你需要这样的东西:

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

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

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

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

关于c# - 表单没有 DragMove() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34863476/

相关文章:

c# - 使用 C# 将 png 文件转换为 pcx 文件

.net - Azure Application_End 未命中,而 Application_Start 多次命中(中间间隔几分钟)

c# - 如何为Windows窗体应用程序设置发布者名称

c# - 当我创建继承自 Form 的新类时,Visual Studio 会更改设计器生成的代码

c# - 找不到 Android 文本文件

c# - 为什么 SignalR Context.User.Identity.Name 是空的?

c# - 单声道 C#。数据行 : "Field" extension method missing?

c# - 在不终止应用程序的情况下处理全局异常?

c# - 如何在 ListView 中使用虚拟模式?

c# - 自定义 WndProc 不会停止调整大小