2013-03-01 221 views
1

通過此代碼,我可以將圖像拖放到標籤上,但現在我想將該圖像從標籤拖動到另一個標籤。我怎樣才能做到這一點?拖放圖像

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)); 
     } 
    } 
} 

回答

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;