C# winforms drag and drop
Hi, trying to implement drag and drop I have custom ToolBox class that simply iherits FlowLayoutPanel, and some picture boxes within. When user clicks on any of these picture boxes, it got copied and added to form's controls just on top of original. Then when user moves mouse around with left button pressed, that picture box should move along, but it don't. It works only if you release mouse button and then click again and move.
Что я уже пробовал:
//want to mentioned that that's not the full code, only what is related to the question public partial class FigureToolBox : FlowLayoutPanel { public delegate void FigureSelected(PictureBox figurePicture,Point location); public event FigureSelected OnFigureSelect; //on mouse down of each picture box public void Figure_mouse_down(object c, MouseEventArgs e) { PictureBox pictureBox = c as PictureBox; PictureBox clonedPicture = new PictureBox(); clonedPicture.SizeMode = PictureBoxSizeMode.AutoSize; clonedPicture.Image = pictureBox.Image; OnFigureSelect(clonedPicture, e.Location); } //some code } public partial class GameForm : Form { Point point = new Point(); //start point of moving PictureBox draggedFig; public GameForm() { InitializeComponent(); figureToolBox1.OnFigureSelect += FigureSelected; } private void FigureSelected(PictureBox box, Point location) { draggedFig = box; //just calculating location of picture box in form's coords Point point = PointToClient(Cursor.Position); box.Left = (point.X- location.X); box.Top = (point.Y- location.Y); this.point = location; this.Controls.Add(draggedFig); draggedFig.BringToFront(); draggedFig.MouseMove += DraggedFig_Move; draggedFig.Focus(); //thought it will help, but it won't } private void DraggedFig_Move(object sender, MouseEventArgs e){ if (e.Button == MouseButtons.Left) { draggedFig.Left += e.X - point.X; draggedFig.Top += e.Y - point.Y; } } }
Member 14015063
Наконец-то понял. Просто нужно было отключить toolbox перед запуском OnFigureSelect:
...
этот.Включен = ложь;
OnFigureSelect(clonedPicture, e.Location);
А затем включите его обратно, когда отпустите кнопку мыши.