首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 拖放功能完整指南:DoDragDrop 方法與五大核心事件深度解析

     編輯:關於C#

一、啟動拖放:DoDragDrop 方法


public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects)
  • data:任意物件,通常為字串、檔案路徑陣列、自訂資料物件。
  • allowedEffects:DragDropEffects 列舉組合(Copy | Move | Link | Scroll | All | None),指定來源端允許的操作。
  • 回傳值:實際發生的效果(Drop 事件中 e.Effect 設定的值)。

典型用法:


private void listBox_MouseDown(object sender, MouseEventArgs e)
{
    if (listBox.SelectedItem != null)
        listBox.DoDragDrop(listBox.SelectedItem, DragDropEffects.Copy | DragDropEffects.Move);
}

二、五大拖放事件時序圖

來源控制項                    目標控制項
   │                              │
   ├─ DoDragDrop ──────────────► │
   │                              ├─ DragEnter (首次進入)
   │                              ├─ DragOver (移動中,高頻觸發)
   │                              ├─ GiveFeedback (來源端,顯示滑鼠游標)
   │                              ├─ QueryContinueDrag (鍵盤/滑鼠狀態變化)
   │                              └─ DragDrop (釋放滑鼠,完成)
   │                              └─ DragLeave (離開未釋放)

三、目標端核心事件處理模板

1. DragEnter:判斷資料格式、設定預設效果


private void target_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.Text) || e.Data.GetDataPresent(DataFormats.FileDrop))
        e.Effect = DragDropEffects.Copy; // 顯示「+」游標
    else
        e.Effect = DragDropEffects.None; // 禁止
}

2. DragOver:即時調整效果(如 Ctrl 鍵切換 Copy/Move)


private void target_DragOver(object sender, DragEventArgs e)
{
    if ((e.KeyState & 8) == 8) // Ctrl 鍵
        e.Effect = DragDropEffects.Copy;
    else
        e.Effect = DragDropEffects.Move;
}

3. DragDrop:取得資料、執行業務邏輯


private void target_DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
        foreach (var f in files) ProcessFile(f);
    }
    else if (e.Data.GetDataPresent(DataFormats.Text))
    {
        string text = (string)e.Data.GetData(DataFormats.Text);
        InsertText(text);
    }
}

4. QueryContinueDrag:來源端控制取消/繼續


private void source_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
{
    if (e.EscapePressed) e.Action = DragAction.Cancel;
    else if (!e.MouseButtons.HasFlag(MouseButtons.Left)) e.Action = DragAction.Drop;
    else e.Action = DragAction.Continue;
}

四、DragEventArgs 關鍵屬性速查

屬性說明
DataIDataObject,含拖放資料
Effect獲取/設定放置效果
AllowedEffect來源端允許的效果
KeyStateShift/Ctrl/Alt + 滑鼠鍵狀態位元組
X, Y螢幕座標

五、進階技巧

  • 自訂資料格式:e.Data.SetData("MyFormat", myObject),配合 GetDataPresent("MyFormat") 實現型別安全拖放。
  • 跨應用程式拖放:只要雙方協定相同格式字串或使用標準格式(FileDrop, Text, Bitmap)即可互通。
  • 效能優化:DragOver 高頻觸發,避免複雜運算;必要時用 GiveFeedback 自訂游標而非預設。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved