我曾在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);
}
}
你可以在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));
}
...
}
源代码与完整的代码。
注意windows vista/windows 7的安全权限——如果你以管理员身份运行Visual Studio,当你在Visual Studio中运行程序时,你将不能将文件从非管理员资源管理器窗口拖到程序中。拖相关事件甚至不会火!
一些示例代码:
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);
}
}
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和