拖放图像
本文关键字:图像 拖放 | 更新日期: 2023-09-27 18:01:36
使用此代码,我可以将图像拖放到标签上,但现在我想将该图像从标签拖放到另一个标签上。我该怎么做呢?
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));
}
}
}
问题是在您的Label
s'拖放处理程序。你可以直接复制拖放操作的'payload',代码如下:
private void Label_DragDrop(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(typeof(Bitmap))) {
((Label)sender).Image = (Image)e.Data.GetData(DataFormats.Bitmap);
}
}
你可能会发现这篇关于拖放的MSDN文章很有用。
我还注意到在你的代码中,MouseDown
, DragEnter
和DragDrop
事件处理程序是相同的多个Button
和Label
控件。您可以通过编写每个处理程序一次,然后将多个控件的事件注册到每个处理程序来稍微重构一些东西。例如,您可以将Label1
和Label10
的DragDrop事件注册到我上面提供的处理程序。在设计器中或通过代码执行:
label1.DragDrop += Label_DragDrop;
label10.DragDrop += Label_DragDrop;