- 标题栏区域封装在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);
- }
- }
[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);
- }
- }