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 (離開未釋放)
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; // 禁止
}
private void target_DragOver(object sender, DragEventArgs e)
{
if ((e.KeyState & 8) == 8) // Ctrl 鍵
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.Move;
}
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);
}
}
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;
}
| 屬性 | 說明 |
|---|---|
Data | IDataObject,含拖放資料 |
Effect | 獲取/設定放置效果 |
AllowedEffect | 來源端允許的效果 |
KeyState | Shift/Ctrl/Alt + 滑鼠鍵狀態位元組 |
X, Y | 螢幕座標 |
e.Data.SetData("MyFormat", myObject),配合 GetDataPresent("MyFormat") 實現型別安全拖放。FileDrop, Text, Bitmap)即可互通。DragOver 高頻觸發,避免複雜運算;必要時用 GiveFeedback 自訂游標而非預設。