winform创建一个可以在主窗体上随意拖动位置的panel,使用异步和双缓存防止卡顿
namespace TestWinForm
{
public partial class Form1 : Form
{
private bool isDragging = false;
private Point lastLocation;
public Form1()
{
InitializeComponent();
panel1.DoubleBuffered(true); // 启用双缓存
panel1.MouseDown += panel1_MouseDown;
panel1.MouseMove += panel1_MouseMove;
panel1.MouseUp += panel1_MouseUp;
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
isDragging = true;
lastLocation = e.Location;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
// 使用异步方法处理拖动,以防止卡顿
MovePanelAsync(e.Location);
}
}
private async void MovePanelAsync(Point newLocation)
{
await Task.Run(() =>
{
// 计算Panel新的位置
int deltaX = newLocation.X - lastLocation.X;
int deltaY = newLocation.Y - lastLocation.Y;
this.Invoke(() =>
{
panel1.Location = new Point(panel1.Location.X + deltaX, panel1.Location.Y + deltaY);
});
});
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
isDragging = false;
}
}
public static class ControlExtensions
{
// 扩展方法:启用双缓存
public static void DoubleBuffered(this Control control, bool enable)
{
var property = typeof(Control).GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
property?.SetValue(control, enable, null);
}
}
}