- private void Form1_Load(object sender, EventArgs e)
- {
- textBox1.AllowDrop = true;
- textBox1.Multiline = true;
- textBox1.DragEnter += new DragEventHandler(textBox1_DragEnter);
- textBox1.DragDrop += new DragEventHandler(textBox1_DragDrop);
- }
- //在将对象拖入控件的边界时发生
- void textBox1_DragEnter(object sender, DragEventArgs e)
- {
- if (Enabled && e.Data.GetDataPresent(DataFormats.FileDrop))
- {
- string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
- files = FileFilter(files);
- if (files.Length > 0)
- {
- e.Effect = DragDropEffects.Copy;
- }
- }
- }
- //在完成拖放操作时发生
- void textBox1_DragDrop(object sender, DragEventArgs e)
- {
- //激活窗体并给予它焦点。
- Activate();
- if (Enabled && e.Data.GetDataPresent(DataFormats.FileDrop))
- {
- string[] allFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
- if (allFiles == null)
- {
- return;
- }
- string[] files = FileFilter(allFiles);
- if (files.Length == 0)
- {
- return;
- }
- else
- {
- //将文件路径添加到文本框中
- foreach (string file in files)
- {
- textBox1.AppendText(file);
- textBox1.AppendText(System.Environment.NewLine); //插入换行符
- }
- }
- }
- }
- //文件过滤
- private string[] FileFilter(string[] fileNames)
- {
- List result = new List();
- foreach (string fileName in fileNames)
- {
- try
- {
- System.IO.FileAttributes fa = System.IO.File.GetAttributes(fileName);
- //如果为文件
- if ((fa & System.IO.FileAttributes.Directory) == 0)
- {
- string ext = System.IO.Path.GetExtension(fileName);
- if (ext.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase)
- || ext.Equals(".gif", StringComparison.CurrentCultureIgnoreCase)
- || ext.Equals(".png", StringComparison.CurrentCultureIgnoreCase)
- || ext.Equals(".bmp", StringComparison.CurrentCultureIgnoreCase)
- || ext.Equals(".jpeg", StringComparison.CurrentCultureIgnoreCase))
- {
- result.Add(fileName);
- }
- }
- }
- catch
- {
- }
- }
- return result.ToArray();
- }
- //该片段来自于http://www.codesnippet.cn/detail/1308201513445.html
来源: http://www.codesnippet.cn/detail/1308201513445.html