在c#实现拖放。一般要用到DragDrap,DragEnter事件和DoDragDrop方法。为了能够完成拖放,一定设置目标控件的AllowDrop属性为true。
(1)DoDragDrop方法启动拖放操作
txtFileName.DoDragDrop(txtFileName.Text, DragDropEffects.Copy|DragDropEffects.Move);
(2)DragEnter事件
当拖动对象进入目标控件时触发。
(3)DragDrop事件
放下拖放内容时触发。
在任何的事件中都可以调用此方法,一般是放在源控件的MouseDown事件中触发。
下面的代码,首先用OpenFileDialog选择一个jpg文件,设置文本框txtFileName的Text属性为该文件的路径。在txtFileName的MouseDown事件中启动拖放操作,拖放数据为图片的路径数据(string类型)。处理picturebox1的DragEnter事件,以显示拖放效果,处理DragDrop事件,根据拖动的文本信息加载图片到picturebox框。
这里要特别注意的事情是在vs集成开发环境中picturebox的AllowDrop属性无法被智能感知,但它确实是存在的,在Form的load事件直接录入就好了。
Code
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opd = new OpenFileDialog();
opd.Filter = "JPEG|*.jpg";
opd.ShowDialog();
this.txtFileName.Text = opd.FileName;
}
private void Form3_Load(object sender, EventArgs e)
{
this.pictureBox1.AllowDrop = true;
}
private void txtFileName_MouseDown(object sender, MouseEventArgs e)
{
//txtFileName.AllowDrop = true;
txtFileName.DoDragDrop(txtFileName.Text, DragDropEffects.Copy|DragDropEffects.Move);
}
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
Bitmap bits = (Bitmap)Bitmap.FromFile(e.Data.GetData(DataFormats.Text).ToString());
pictureBox1.Image = bits;
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opd = new OpenFileDialog();
opd.Filter = "JPEG|*.jpg";
opd.ShowDialog();
this.txtFileName.Text = opd.FileName;
}
private void Form3_Load(object sender, EventArgs e)
{
this.pictureBox1.AllowDrop = true;
}
private void txtFileName_MouseDown(object sender, MouseEventArgs e)
{
//txtFileName.AllowDrop = true;
txtFileName.DoDragDrop(txtFileName.Text, DragDropEffects.Copy|DragDropEffects.Move);
}
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
Bitmap bits = (Bitmap)Bitmap.FromFile(e.Data.GetData(DataFormats.Text).ToString());
pictureBox1.Image = bits;
}