C#实现无标题栏窗体的拖动

无标题栏窗体,也就是FormBorderStyle等于System.Windows.Forms.FormBorderStyle.None的窗体。要实现无标题栏窗体的拖动,分2种情况讨论:

  • 标题栏区域封装在Panel容器内(推荐方案),则编写该Panel的MouseDown事件处理函数。

[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern bool ReleaseCapture(); private void panelCaption_MouseDown(object sender, MouseEventArgs e) { const int WM_NCLBUTTONDOWN = 0x00A1; const int HTCAPTION = 2; if (e.Button == MouseButtons.Left) // 按下的是鼠标左键 { ReleaseCapture(); SendMessage(this.Handle, WM_NCLBUTTONDOWN, (IntPtr)HTCAPTION, IntPtr.Zero); // 拖动窗体 } }

  • 标题栏区域直接放置在窗体上,则重写该窗体的OnMouseDown函数。

 [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern bool ReleaseCapture(); protected override void OnMouseDown( MouseEventArgs e ) { const int WM_NCLBUTTONDOWN = 0x00A1; const int HTCAPTION = 2; base.OnMouseDown( e ); if (e.Button == MouseButtons.Left) // 按下的是鼠标左键 { ReleaseCapture(); // 释放捕获 SendMessage(this.Handle, WM_NCLBUTTONDOWN, (IntPtr)HTCAPTION, IntPtr.Zero); // 拖动窗体 } }

你可能感兴趣的:(object,C#,user)