C# 实现无边框窗体 TableLayoutPanel 拖动
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public partial class MainForm : Form
{
private const int WM_NCLBUTTONDOWN = 0xA1; // 鼠标按下消息
private const int HT_CAPTION = 0x2; // 标题栏区域
[DllImport('user32.dll')]
private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); // 发送消息
[DllImport('user32.dll')]
private static extern bool ReleaseCapture(); // 释放鼠标捕获
public MainForm()
{
InitializeComponent();
// 添加鼠标事件处理程序到拖动区域的 MouseDown 事件
panelDrag.MouseDown += new MouseEventHandler(panelDrag_MouseDown);
}
private void panelDrag_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left) // 按下左键
{
ReleaseCapture(); // 释放鼠标捕获
SendMessage(this.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); // 发送拖动消息给窗体
}
}
}
}
以上代码演示了如何在 C# 中实现无边框窗体中包含多个 TableLayoutPanel 的拖动功能。
代码解释:
WM_NCLBUTTONDOWN和HT_CAPTION是用于模拟标题栏拖动行为的 Windows 消息常量。SendMessage函数用于向窗体发送消息,这里是发送鼠标按下消息到标题栏区域,以触发窗体移动。ReleaseCapture函数用于释放鼠标捕获,允许窗体接收鼠标移动消息。- 在
panelDrag_MouseDown事件处理程序中,当鼠标左键在panelDrag控件上按下时,代码会释放鼠标捕获并发送拖动消息,从而实现拖动功能。
使用方法:
- 将
panelDrag替换为你实际使用的Panel控件的名称。 - 将此代码添加到你的窗体代码中。
通过以上步骤,你就可以实现无边框窗体中 TableLayoutPanel 的拖动功能了。
原文地址: https://www.cveoy.top/t/topic/lAh 著作权归作者所有。请勿转载和采集!