日期:2014-05-18  浏览次数:20925 次

拖动文件到文本框,如何得到路径?
如题,现在有一个文本框,TextBox1,allowdrop设置为true,未做其他设置,怎么才能让一个文件拖到上面就显示这个文件的路径(最好绝对路径)呢??翻书没翻到。

------解决方案--------------------
设置textBox1的DragEnter和DragDrop事件,然后在事件里这么填就行。

C# code

        private void textBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void textBox1_DragDrop(object sender, DragEventArgs e)
        {
            String[] files = (String[])e.Data.GetData(DataFormats.FileDrop, false);
            if (files.Length > 0)
            {
                textBox1.Text = files[0];
            }
        }

------解决方案--------------------
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

this.textBox1.Multiline = true;
this.textBox1.AllowDrop = true;
this.textBox1.DragDrop+=new DragEventHandler(textBox1_DragDrop);
this.textBox1.DragEnter+=new DragEventHandler(textBox1_DragEnter);
}

protected void textBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
IDataObject dataObject = e.Data;
if (dataObject.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
}

protected void textBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{

IDataObject dataObject = e.Data;

if (dataObject == null) return;

if (dataObject.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])dataObject.GetData(DataFormats.FileDrop);

foreach (string file in files)
{
System.IO.FileInfo fi = new System.IO.FileInfo(file);
this.textBox1.Text += "文件名:" + fi.Name;

}

}
}

}