C# 拖拽操作

Overiew

今天我们来看一下如何实现我们的拖拽事件。

C#的拖拽

有两个主要的事件:
DragEnter 拖拽到区域中触发的事件
DragDrop 当拖拽落下的时候发出此事件
学习博客:https://www.cnblogs.com/slyfox/p/7116647.html

从ListBox拖拽到另一个ListBox

using System;
using System.Windows.Forms;

namespace StudyDrag
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

}

void Init()
{
this.listBox1.AllowDrop = true;
this.treeView1.AllowDrop = true;
this.listBox2.AllowDrop = true;
}

void LoadData()
{
//加载数据
for (int i = 1; i <= 10; i++)
{
string itemValue = "有关部门" + i.ToString();
this.listBox1.Items.Add(itemValue);
}
}

private void Form1_Load(object sender, EventArgs e)
{
Init();
LoadData();
}

///


/// 鼠标点击的时候开始执行拖拽操作
///

///
///
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
if (this.listBox1.SelectedItem != null)
{
this.listBox1.DoDragDrop(this.listBox1.SelectedItem, DragDropEffects.Copy);
}
}

///


/// 当拖拽完成后触发的事件
///

///
///
private void ListBox2_DragDrop(object sender, DragEventArgs e)
{
string item = (string)e.Data.GetData(DataFormats.Text);
this.listBox2.Items.Add(item);
}

///


/// 当拖拽进去区域后触发的事件
///

///
///
private void ListBox2_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
}

}

这样我们就完成了我们的拖拽事件。

posted @ 2020-04-16 08:28  Leo726  阅读(1719)  评论(0)    收藏  举报