C# winform中无标题栏窗口如何实现鼠标拖动?

时间:2024-11-18 11:52:15
public partial class Form1 : Form { private bool isDragging = false; private Point lastCursor; private Point lastForm; public Form1() { InitializeComponent(); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left) { isDragging = true; lastCursor = Cursor.Position; lastForm = this.Location; } } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (isDragging) { int xDiff = Cursor.Position.X - lastCursor.X; int yDiff = Cursor.Position.Y - lastCursor.Y; this.Location = new Point(lastForm.X + xDiff, lastForm.Y + yDiff); } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (e.Button == MouseButtons.Left) { isDragging = false; } } }