1. 程式人生 > 其它 >winform控制元件拖動

winform控制元件拖動

示例程式碼

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
public static class ControlDrag
{
    static Dictionary<string, Point> _locationList = new Dictionary<string, Point>();
    static Dictionary<string, bool> _isDownList = new Dictionary<string
, bool>();
//擴充套件函式
public static void AddDrag(this Control control) { if (_locationList.ContainsKey(control.Name)==false) { _locationList.Add(control.Name, new Point() ); _isDownList.Add(control.Name, false);         
        
//按下滑鼠 control.MouseDown
+= (s, ev) => { _isDownList[control.Name] = true; _locationList[control.Name] = new Point(ev.X, ev.Y); }; //鬆開滑鼠 control.MouseUp += (s, ev) => { _isDownList[control.Name] = false; }; //滑鼠移動 control.MouseMove
+= (s, ev) => { if (_isDownList[control.Name]) { int left = control.Left + ev.X - _locationList[control.Name].X; int top = control.Top + ev.Y - _locationList[control.Name].Y; control.Location = new Point(left, top); } }; } } }

呼叫方式

private void Form1_Load(object sender, EventArgs e)
{

//可以是任何控制元件
panel1.AddDrag();
//可以是任何控制元件
label1.AddDrag();

}