[英]How do I drag and drop files into an application?
一些示例代碼:
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);
}
}
請注意 windows vista/windows 7 安全權限 - 如果您以管理員身份運行 Visual Studio,當您從 Visual Studio 中運行時,您將無法將文件從非管理員資源管理器窗口拖到您的程序中。 與拖動相關的事件甚至不會觸發! 我希望這可以幫助其他人不要浪費他們的生命......
在 Windows 窗體中,設置控件的 AllowDrop 屬性,然后偵聽 DragEnter 事件和 DragDrop 事件。
當DragEnter
事件觸發時,將參數的AllowedEffect
設置為非無(例如e.Effect = DragDropEffects.Move
)。
當DragDrop
事件觸發時,您將獲得一個字符串列表。 每個字符串都是要刪除的文件的完整路徑。
你需要知道一個陷阱。 在拖放操作中作為DataObject傳遞的任何類都必須是可序列化的。 因此,如果您嘗試傳遞一個對象,但它不起作用,請確保它可以被序列化,因為這幾乎肯定是問題所在。 這讓我抓到了好幾次!
另一個問題:
調用 Drag-events 的框架代碼會吞下所有異常。 您可能會認為您的事件代碼運行平穩,而它卻到處涌現異常。 您看不到它們,因為框架竊取了它們。
這就是為什么我總是在這些事件處理程序中放置一個 try/catch,這樣我就知道它們是否會拋出任何異常。 我通常放一個 Debugger.Break(); 在捕獲部分。
在發布之前,在測試之后,如果一切似乎都正常,我會刪除或用真正的異常處理替換它們。
這是我用來刪除文件和/或充滿文件的文件夾的東西。 在我的情況下,我只過濾*.dwg
文件並選擇包含所有子文件夾。
fileList
是IEnumerable
或類似的在我的情況下綁定到 WPF 控件...
var fileList = (IList)FileList.ItemsSource;
有關該技巧的詳細信息,請參閱https://stackoverflow.com/a/19954958/492 。
下降處理程序...
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);
}
}
另一個常見的問題是認為您可以忽略 Form DragOver(或 DragEnter)事件。 我通常使用 Form 的 DragOver 事件來設置 AllowedEffect,然后使用特定控件的 DragDrop 事件來處理拖放的數據。
您可以在 WinForms 和 WPF 中實現拖放。
您應該添加 mousemove 事件:
private void YourElementControl_MouseMove(object sender, MouseEventArgs e)
{
...
if (e.Button == MouseButtons.Left)
{
DoDragDrop(new DataObject(DataFormats.FileDrop, new string[] { PathToFirstFile,PathToTheNextOne }), DragDropEffects.Move);
}
...
}
您應該添加 DragDrop 事件:
私人無效YourElementControl_DragDrop(對象發送者,DragEventArgs e)
{
...
foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop))
{
File.Copy(path, DirPath + Path.GetFileName(path));
}
...
}
請注意,為此,您還需要在 _drawEnter 中設置 dragDropEffect...
private void Form1_DragEnter(object sender, DragEventArgs e)
{
Console.WriteLine("DragEnter!");
e.Effect = DragDropEffects.Copy;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.