我曾在Borland的Turbo c++环境中看到过这一点,但我不确定如何在我正在开发的c#应用程序中实现这一点。是否有最佳实践或陷阱需要注意?
当前回答
这是我用来放置文件和/或文件夹充满文件的东西。在我的例子中,我过滤的是*。DWG文件,并选择包括所有子文件夹。
fileList是一个IEnumerable或类似的在我的情况下被绑定到一个WPF控件…
var fileList = (IList)FileList.ItemsSource;
详见https://stackoverflow.com/a/19954958/492。
drop Handler…
private void FileList_OnDrop(object sender, DragEventArgs e)
{
var dropped = ((string[])e.Data.GetData(DataFormats.FileDrop));
var files = dropped.ToList();
if (!files.Any())
return;
foreach (string drop in dropped)
if (Directory.Exists(drop))
files.AddRange(Directory.GetFiles(drop, "*.dwg", SearchOption.AllDirectories));
foreach (string file in files)
{
if (!fileList.Contains(file) && file.ToLower().EndsWith(".dwg"))
fileList.Add(file);
}
}
其他回答
注意windows vista/windows 7的安全权限——如果你以管理员身份运行Visual Studio,当你在Visual Studio中运行程序时,你将不能将文件从非管理员资源管理器窗口拖到程序中。拖相关事件甚至不会火!
注意,为了实现这一点,你还需要在_drawEnter…中设置dragDropEffect。
private void Form1_DragEnter(object sender, DragEventArgs e)
{
Console.WriteLine("DragEnter!");
e.Effect = DragDropEffects.Copy;
}
来源:在c# Winforms应用程序中拖放不工作
你可以在WinForms和WPF中实现拖放。
WinForm(从应用程序窗口拖动)
你应该添加鼠标移动事件:
private void YourElementControl_MouseMove(object sender, MouseEventArgs e)
{
...
if (e.Button == MouseButtons.Left)
{
DoDragDrop(new DataObject(DataFormats.FileDrop, new string[] { PathToFirstFile,PathToTheNextOne }), DragDropEffects.Move);
}
...
}
WinForm(拖到应用程序窗口)
你应该添加DragDrop事件:
private void YourElementControl_DragDrop(对象发送者,DragEventArgs e)
{
...
foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop))
{
File.Copy(path, DirPath + Path.GetFileName(path));
}
...
}
源代码与完整的代码。
Judah Himango和Hans Passant的解决方案在设计器中可用(我目前使用VS2015):
一些示例代码:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.AllowDrop = true;
this.DragEnter += new DragEventHandler(Form1_DragEnter);
this.DragDrop += new DragEventHandler(Form1_DragDrop);
}
void Form1_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
void Form1_DragDrop(object sender, DragEventArgs e) {
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files) Console.WriteLine(file);
}
}
推荐文章
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 为什么控制台不。Writeline,控制台。在Visual Studio Express中编写工作?
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何在c#中连接列表?
- 在c#中引用类型变量的“ref”的用途是什么?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?