private void listView1_ItemDrag(object sender, ItemDragEventArgs e) { ListViewItem item = (ListViewItem)e.Item; string itemName = item.Text; listView1.DoDragDrop(itemName, DragDropEffects.Copy); },将listview中的值拖拽到picturebox上后并且使用drawstring显示出来后,如何在picturebox上随意拖拽刚刚显示在picturebox上的数据,要求所有拖拽过来的数据都可以移动位置,代码该如何实现
时间: 2023-05-20 18:05:34 浏览: 38
您可以使用以下代码实现在picturebox上随意拖拽刚刚显示在picturebox上的数据:
private Point _mouseDownLocation;
private bool _isDragging = false;
private List<string> _draggedItems = new List<string>();
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
_mouseDownLocation = e.Location;
_isDragging = true;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (_isDragging)
{
foreach (string item in _draggedItems)
{
using (Graphics g = pictureBox1.CreateGraphics())
{
g.Clear(Color.White);
g.DrawString(item, Font, Brushes.Black, e.X - _mouseDownLocation.X, e.Y - _mouseDownLocation.Y);
}
}
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
_isDragging = false;
}
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
e.Effect = DragDropEffects.Copy;
}
}
private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
string itemName = (string)e.Data.GetData(typeof(string));
_draggedItems.Add(itemName);
using (Graphics g = pictureBox1.CreateGraphics())
{
g.DrawString(itemName, Font, Brushes.Black, e.X - _mouseDownLocation.X, e.Y - _mouseDownLocation.Y);
}
}
}
在listview的ItemDrag事件中,您可以将拖拽的项的文本存储在一个列表中,然后在picturebox的MouseDown和MouseMove事件中,使用Graphics对象在picturebox上绘制所有拖拽过来的项的文本。在picturebox的MouseUp事件中,将_isDragging标志设置为false。在picturebox的DragEnter和DragDrop事件中,您可以使用相同的代码来处理拖放操作。