如何删除C#中创建的图像?
我有它,用户可以点击一个图像视图并将项目拖到表单的其他地方,这样做可以创建一个新图像,而原始图像框保持不变。如何在单击时删除其中一个复制的图像如何删除C#中创建的图像?,c#,winforms,onclick,picturebox,C#,Winforms,Onclick,Picturebox,我有它,用户可以点击一个图像视图并将项目拖到表单的其他地方,这样做可以创建一个新图像,而原始图像框保持不变。如何在单击时删除其中一个复制的图像 public partial class Form1 : Form { public Form1() { InitializeComponent(); this.AllowDrop = true; this.pictureBox1.MouseDown += pictureBox1_Mouse
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.AllowDrop = true;
this.pictureBox1.MouseDown += pictureBox1_MouseDown;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
var dragImage = (Bitmap)pictureBox1.Image;
IntPtr icon = dragImage.GetHicon();
Cursor.Current = new Cursor(icon);
DoDragDrop(pictureBox1.Image, DragDropEffects.Copy);
DestroyIcon(icon);
}
}
protected override void OnGiveFeedback(GiveFeedbackEventArgs e)
{
e.UseDefaultCursors = false;
}
protected override void OnDragEnter(DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Bitmap))) e.Effect = DragDropEffects.Copy;
}
protected override void OnDragDrop(DragEventArgs e)
{
var bmp = (Bitmap)e.Data.GetData(typeof(Bitmap));
var pb = new PictureBox();
pb.Image = (Bitmap)e.Data.GetData(typeof(Bitmap));
pb.Size = pb.Image.Size;
pb.Location = this.PointToClient(new Point(e.X - pb.Width / 2, e.Y - pb.Height / 2));
this.Controls.Add(pb);
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
extern static bool DestroyIcon(IntPtr handle);
}
只需在拖放后添加删除操作
protected override void OnDragDrop(DragEventArgs e) {
var pb = new PictureBox {
Image = (Bitmap)e.Data.GetData(typeof(Bitmap))
};
pb.Size = pb.Image.Size;
pb.Location = PointToClient(new Point(e.X - pb.Width / 2, e.Y - pb.Height / 2));
Controls.Add(pb);
// deletion here: Controls.Remove(pictureBox1 or pb);
base.OnDragDrop(e);
}
如果您希望在其他地方删除它,则需要在类级别声明一个变量,并用“pb”赋值。然后,在给定pictureBox1和pb的情况下,您可以决定删除哪一个