【IT168技术文档】
用DoDragDrop可以做到的
首先, 封装一个DragDropObject的Class
C# code
再封装一个Helper类public class MovingObject { protected Control control; public MovingObject(Control ctrl) { control = ctrl; } public Control MovingControl { get { return control; } } }
C# code
OK, 现在随便写一个Form2作为Test用的一个子窗体, 上面只摆一个ListBox控件public class User32 { [DllImport("User32.dll")] public static extern int GetWindowRect(IntPtr handle, ref Rectangle rect); }
C# code
public partial class Form2 : Form { public Form2() { InitializeComponent(); AllowDrop = true; listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown); DragEnter += new DragEventHandler(Form2_DragEnter); DragDrop += new DragEventHandler(Form2_DragDrop); } void Form2_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(typeof(MovingObject))) { MovingObject movingObj = e.Data.GetData(typeof(MovingObject)) as MovingObject; if (movingObj != null) { Rectangle rect = Rectangle.Empty; User32.GetWindowRect(Handle, ref rect); movingObj.MovingControl.Location = new Point(e.X - rect.Location.X - 6, e.Y - rect.Location.Y - 34); Controls.Add(movingObj.MovingControl); } } } void Form2_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(typeof(MovingObject))) e.Effect = DragDropEffects.Copy; } void listBox1_MouseDown(object sender, MouseEventArgs e) { DoDragDrop(new MovingObject(listBox1), DragDropEffects.Copy); } }