[英]C# drag and drop picturebox
I have 7 pictureboxes and I want to drag and drop each one of them. 我有7个图片框,我想拖放其中的每一个。 I have made the drag and drop but it takes with it the original picturebox which I drag it doesn't leave it on its place. 我已经进行了拖放,但是它带有原始图片框,而我拖动它并不会把它留在原处。 This is my code: 这是我的代码:
this.pbAND.MouseDown += pictureBox_MouseDown;
pbAND.MouseMove += pictureBox_MouseMove;
pbAND.MouseUp += pictureBox_MouseUp;
this.pbOR.MouseDown += pictureBox_MouseDown;
pbOR.MouseMove += pictureBox_MouseMove;
pbOR.MouseUp += pictureBox_MouseUp;
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
p = (PictureBox)sender;
downPoint = e.Location;
var dragImage = (Bitmap)p.Image;
IntPtr icon = dragImage.GetHicon();
Cursor.Current = new Cursor(icon);
p.Parent = this;
p.BringToFront();
DestroyIcon(icon);
}
}
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
p = (PictureBox)sender;
if (e.Button == MouseButtons.Left)
{
p.Left += e.X - downPoint.X;
p.Top += e.Y - downPoint.Y;
}
}
private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
p = (PictureBox)sender;
Control c = GetChildAtPoint(new Point(p.Left - 1, p.Top));
if (c == null) c = this;
Point newLoc = c.PointToClient(p.Parent.PointToScreen(p.Location));
p.Parent = c;
p.Location = newLoc;
}
but it takes with it the original picturebox which I drag it doesn't leave it on its place. 但它带有原始图片框(我拖动它)不会将其留在原处。
So you want to make a copy when the PictureBox is dropped? 所以要在放下PictureBox时进行复制吗?
In the MouseDown() handler, store the original location in the Tag() property: 在MouseDown()处理程序中,将原始位置存储在Tag()属性中:
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
p = (PictureBox)sender;
p.Tag = p.Location; // <-- store the Location in the Tag() property
// ... rest of the existing code ...
}
}
In the MouseUp() handler, put a New PictureBox in the current location and reset the original: 在MouseUp()处理程序中,在当前位置放置一个New PictureBox并重置原始图片:
private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
p = (PictureBox)sender;
// create a new PictureBox that looks like the original:
PictureBox PB = new PictureBox();
PB.Size = p.Size;
PB.Image = p.Image;
PB.SizeMode = p.SizeMode;
PB.BorderStyle = p.BorderStyle;
// etc...make it look the same
// ...and place it:
Control c = GetChildAtPoint(new Point(p.Left - 1, p.Top));
if (c == null) c = this;
Point newLoc = c.PointToClient(p.Parent.PointToScreen(p.Location));
PB.Parent = c;
PB.Location = newLoc;
p.Parent.Controls.Add(PB); // <-- add new PB to the form!
// put the original back where it started:
p.Location = (Point)p.Tag;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.