WinForm实现简单的拖拽功能(C#)(2)

时间:2022-04-13 12:56:10

首先创建一个winform应用程序,添加listbox1与listbox2,拖拽listbox1的项到listbox2上去。

具体代码如下

namespace OLE拖拽
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
listBox1.AllowDrop = true;
listBox2.AllowDrop = true;
listBox1.Items.Add("11");
listBox1.Items.Add("22");
listBox1.Items.Add("33");
SetCtrlDrag.SetCtrlDragEvent(this.textBox1);
}

private void listBox1_MouseDown(object sender, MouseEventArgs e)
{

this.listBox1.DoDragDrop(this.listBox1.Items[this.listBox1.SelectedIndex], DragDropEffects.Move);
//MessageBox.Show("开始拖拽操作了");
}

private void listBox2_DragEnter(object sender, DragEventArgs e)
{
//MessageBox.Show("拖拽进入时");
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Move;
}
}

private void listBox2_DragDrop(object sender, DragEventArgs e)
{
//MessageBox.Show("拖放");
this.listBox2.Items.Add(e.Data.GetData(DataFormats.Text));
this.listBox1.Items.Remove(e.Data.GetData(DataFormats.Text));
}
}
public class SetCtrlDrag
{
public static void SetCtrlDragEvent(Control ctrl)
{
if (ctrl is TextBox)
{
TextBox textBox = ctrl as TextBox;
textBox.AllowDrop = true;
textBox.DragEnter += (sender, e) =>
{
e.Effect = DragDropEffects.Link;
};
textBox.DragDrop += (sender, e) =>
{
((TextBox)sender).Text = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
};
}
}
}
}