1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
|
namespace WinDragDrogListboc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// ListDragSource
this.listBoxSrc.Items.AddRange(new object[] {"one", "two", "three", "four",
"five", "six", "seven", "eight","nine", "ten"});
this.listBoxSrc.MouseDown += new MouseEventHandler(listBoxSrc_MouseDown);
this.listBoxSrc.MouseMove += new MouseEventHandler(listBoxSrc_MouseMove);
this.listBoxSrc.MouseUp += new MouseEventHandler(listBoxSrc_MouseUp);
this.comboBoxDst.AllowDrop = true;// combo autorise le drop
this.comboBoxDst.DragDrop += new DragEventHandler(comboBoxDst_DragDrop);
this.comboBoxDst.DragEnter += new DragEventHandler(comboBoxDst_DragEnter);
}
private Point screenOffset;
private int indexItem;
private Rectangle dragBox;
void listBoxSrc_MouseDown(object sender, MouseEventArgs e)
{
indexItem = listBoxSrc.IndexFromPoint(e.X, e.Y);
if (indexItem != ListBox.NoMatches)
{
Size dragSize = SystemInformation.DragSize;
dragBox = new Rectangle(new Point(e.X - (dragSize.Width / 2),
e.Y - (dragSize.Height / 2)), dragSize);
}
else
dragBox = Rectangle.Empty;
}
void listBoxSrc_MouseMove(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// If the mouse moves outside the rectangle, start the drag.
if (dragBox != Rectangle.Empty &&
!dragBox.Contains(e.X, e.Y))
{
screenOffset = SystemInformation.WorkingArea.Location;
DragDropEffects dropEffect = listBoxSrc.DoDragDrop(listBoxSrc.Items[indexItem], DragDropEffects.Move);
// If the drag operation was a move then remove the item.
if (dropEffect == DragDropEffects.Move)
{
listBoxSrc.Items.RemoveAt(indexItem);
if (indexItem > 0)
listBoxSrc.SelectedIndex = indexItem -1;
else if (listBoxSrc.Items.Count > 0)
listBoxSrc.SelectedIndex = 0;
}
}
}
}
void listBoxSrc_MouseUp(object sender, MouseEventArgs e)
{
//reset rectangle
dragBox = Rectangle.Empty;
}
void comboBoxDst_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
e.Effect = DragDropEffects.Move;
}
void comboBoxDst_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
Object item = (object)e.Data.GetData(typeof(System.String));
if (e.Effect == DragDropEffects.Copy ||
e.Effect == DragDropEffects.Move)
{
// Insert or Add the item .
int index = this.comboBoxDst.Items.Count - 1;
if (index == -1)
this.comboBoxDst.Items.Add(item);
else
this.comboBoxDst.Items.Insert(index+1, item);
}
}
}
}
} |
Partager