拖放图像

时间:2013-03-01 06:09:38

标签: c# .net winforms

使用此代码,我可以将图像拖放到标签上,但现在我想将该图像从标签拖到另一个标签。我怎么能这样做?

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            Image img = Image.FromFile(@"D:\test\test.png");
            this.btnImage.Image = img;

            Image img1 = Image.FromFile(@"C:\Documents and Settings\SAURABH\Desktop\Green.ico");
            this.btnImage1.Image = img1;
        }

        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            Button btnPic = (Button)sender;
            btnPic.DoDragDrop(btnPic.Image, DragDropEffects.Copy);
        }

        private void button2_MouseDown(object sender, MouseEventArgs e)
        {
            Button btnPic = (Button)sender;
            btnPic.DoDragDrop(btnPic.Image, DragDropEffects.Copy);
        }

        private void button3_MouseDown(object sender, MouseEventArgs e)
        {
            Button btnPic = (Button)sender;
            btnPic.DoDragDrop(btnPic.Image, DragDropEffects.Copy);
        }

        private void label1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Bitmap))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void label10_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Bitmap))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void label10_DragDrop(object sender, DragEventArgs e)
        {
            Label picbox = (Label)sender;
            //PictureBox picbox = (PictureBox)sender;
            Graphics g = picbox.CreateGraphics();
            g.DrawImage((Image)e.Data.GetData(DataFormats.Bitmap), new Point(0, 0));
        }

        private void label1_DragDrop(object sender, DragEventArgs e)
        {
            Label picbox = (Label)sender;
            //PictureBox picbox = (PictureBox)sender;
            Graphics g = picbox.CreateGraphics();
            g.DrawImage((Image)e.Data.GetData(DataFormats.Bitmap), new Point(0, 0));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题出在你的Label''DragDrop处理程序中。您可以使用以下代码直接复制拖放操作的“有效负载”:

private void Label_DragDrop(object sender, DragEventArgs e) {
    if (e.Data.GetDataPresent(typeof(Bitmap))) {
        ((Label)sender).Image = (Image)e.Data.GetData(DataFormats.Bitmap);
    }
}

您可能会发现拖放时this MSDN article很有用。

我还在您的代码中注意到MouseDownDragEnterDragDrop事件处理程序对于多个ButtonLabel控件都是相同的。您可以通过编写这些处理程序一次,然后将多个控件的事件注册到每个处理程序来重构一些事情。例如,您可以将Label1Label10的DragDrop事件注册到我上面提供的处理程序。在Designer中执行此操作,或通过代码执行此操作:

label1.DragDrop += Label_DragDrop;
label10.DragDrop += Label_DragDrop;