Skip to main content
 首页 » 编程设计

c#之表单没有 DragMove() 方法

2024年02月05日16luoye11

所以无论单击什么元素我都需要移动我的表单(我需要通过按住按钮拖动表单,表单是 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 事件更新为类似于上面的代码,任何控件都可以用于拖动窗口。