[轉貼] 最簡單 Drag Drop 範例使用

2013052218:20
出處: http://debut.cis.nctu.edu.tw/~ching/Course/AdvancedC++Course/__Page/ProgramTips/ProgramTech_DragDrop.html

有時候, 直接從檔案總管拉檔案進到應用程式中, 反而比較快而且有效率. 這種功能在程式設計裡面, 叫做 Drag and Drop (拖拉, 丟下), ... 在 MFC, Java 到現在的 C# 都有提供這方便的功能

雖然在 C# 中 是一個簡單的設定, 但是卻讓我搞了很久.

直接從 MSDN來看, 要讓元件允許被 Drag Drop, 只要設定 屬性 AllowDrop =true.

然而這樣的設定是不夠的. 你還要在 DragEnter 事件處理函式中, 設定事件屬性 Effect=DragDropEffects.All. 才會正式的啟動 DragDrop 的功能.

這東西的設定目的在於防止使用者, 隨便倒東西到你的應用程式, 也就是說, 你可以設定應用程式哪些可以吃那些不能吃.

都可以在 DragEnter 事件處理函式, 藉由設定 Effect 屬性來完成.

我們現在就來看看範例吧.

最簡單範例

準備工作
1. 建立一個 Form, 並且拉一個 listBox 元件到上面
2. 命名 listBox 為 listBox_FileList

執行步驟 
// Step 1: 拖拉功能啟動
this.listBox_FileList.AllowDrop = true;

// Step 2: 在 listBox_FileList 的 DragEnter 事件中, 加入下面程式碼
private void listBox_FileList_DragEnter(object sender, DragEventArgs e)
{
// 確定使用者抓進來的是檔案
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
// 允許拖拉動作繼續 (這時滑鼠游標應該會顯示 +)
e.Effect = DragDropEffects.All;
}
}

// Step 3: 在 listBox_FileList 的 DragDrop 事件中, 加入下面程式碼
private void listBox_FileList_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
listBox_FileList.Items.Add(file);
}
}

完成 !!

延伸讀物

1. Jim Parsell 先生的文章: http://www.codeproject.com/vb/net/ExpTreeDragDrop.asp

2. Michael Dunn 先生的文章: How to Implement Drag and Drop Between Your Program and Explorer

3. Steven Robert 先生, 使用 Win32 API 增強了 C# Drag Drop 功能的專案文章 : http://www.codeproject.com/useritems/FileBrowser.asp