将文件拖入文本框

将文件拖入文本框

本文介绍了将文件拖入文本框,WinForm C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

而不是使用以下命令加载文件:

Instead of loading a file with a:

OpenFileDialog ofd = new OpenFileDialog ();


如何将文件拖到文本框中,然后在文本框中显示文件路径?

谢谢
KZ


How do I drag the file into a text box and text box then displays the file path?

Thank you,
KZ

推荐答案

public class MyTextBox : TextBox
    {
    public MyTextBox()
        {
        AllowDrop = true;
        Multiline = true;
        DragDrop += new DragEventHandler(MyTextBox_DragDrop);
        DragEnter += new DragEventHandler(MyTextBox_DragEnter);
        }

    void MyTextBox_DragEnter(object sender, DragEventArgs e)
        {
        e.Effect = DragDropEffects.Copy;
        }

    void MyTextBox_DragDrop(object sender, DragEventArgs e)
        {
        DataObject data = (DataObject)e.Data;
        if (data.ContainsFileDropList())
            {
            string[] rawFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (rawFiles != null)
                {
                List<string> lines = new List<string>();
                foreach (string path in rawFiles)
                    {
                    lines.AddRange(File.ReadAllLines(path));
                    }
                Lines = lines.ToArray();
                }
            }
        }
     }



[edit]
糟糕!走了一点...那会显示文件内容,而不是路径.路径更容易:只需替换



[edit]
Oops! Went a little far there...That displays the file content, rather than path. Path is even easier: just replace

lines.AddRange(File.ReadAllLines(path));




With

lines.Add(path);


-OriginalGriff
[/edit]


- OriginalGriff
[/edit]


这篇关于将文件拖入文本框,WinForm C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:16