如何在Panel移动窗体窗口中创建mousedrag?

我有这个我想要启用的System.Windows.Forms.Panel,这样如果用户点击并拖动鼠标拖动窗口到。

我可以这样做吗? 我必须实施多个活动吗?

您可以使用面板的MouseMove事件来实现它

示例应该是这样的(抱歉没有测试过)

private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.Location = new Point(Cursor.Position.X + eX , Cursor.Position.Y + eY); } } 

最适合我的解决方案是使用非托管代码,与HatSoft发布的答案不同,它可以为您提供平滑的窗口移动。

3个小步骤在Panel移动上拖动窗口

 using System.Runtime.InteropServices; 

在你的课程中添加这六行

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

Panel上的MouseMove事件应如下所示

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

发布它有点晚了:),谁知道我们将来可能会再次需要它。

您可能想看一下我粘贴在此处的组件:

http://pastebin.com/5ufJmuay

它是一个可以放在表单上的组件,然后通过在其中拖动来拖动表单。

Bravo的代码工作得非常好,但是在我想要移动的面板的 – > properties-> event部分中明确地使MouseMove事件启用之前我无法正常工作。