Drag and drop, and the clipboard

Dragging a file from Explorer onto a window, or a row from a list onto a calendar, is the gesture a desktop application is expected to understand. In WinForms it is a property on the target, AllowDrop, a method on the source, DoDragDrop, and four events on the target that pronounce judgement on what is being carried. The clipboard is the same data in a slower form, and the two share one type, DataObject.

A drop target

using System; using System.Drawing; using System.IO; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } internal sealed class Form1 : Form { private readonly ListBox _files = new() { Location = new Point(16, 16), Size = new Size(340, 160), AllowDrop = true, }; public Form1() { Text = "Drop files here"; ClientSize = new Size(380, 200); _files.DragEnter += OnDragEnter; _files.DragDrop += OnDragDrop; Controls.Add(_files); } private void OnDragEnter(object? sender, DragEventArgs e) { var formats = e.Data?.GetFormats() ?? Array.Empty<string>(); e.Effect = e.Data?.GetDataPresent(DataFormats.FileDrop) == true ? DragDropEffects.Copy : DragDropEffects.None; if (formats.Length == 0) { return; } } private void OnDragDrop(object? sender, DragEventArgs e) { if (e.Data?.GetData(DataFormats.FileDrop) is not string[] paths) { return; } foreach (var path in paths) { _files.Items.Add(Path.GetFileName(path)); } } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. Three lines matter. AllowDrop = true is what makes the control a target at all; a control that does not set it receives no drag events and the pointer shows the no-drop cursor. e.Effect in DragEnter is the answer to "will you take this": None draws the forbidden cursor and means the drop never happens. And the data arrives as FileDrop, which is a string[] of full paths, not as a list of names.

Formats and effects

A drag carries a DataObject, which can hold several formats at once and lets the target choose. The formats every application knows are in DataFormats:

The effects are the target's choice: DragDropEffects.Copy, Move, Link and None, combined with | when more than one is allowed. The cursor changes with the effect, and the source learns the result as the return value of DoDragDrop, which is how a list knows whether to remove the row it just dragged:

using System; using System.Drawing; using System.Windows.Forms; internal sealed class Form1 : Form { private readonly ListBox _source = new() { Location = new Point(16, 16), Size = new Size(160, 120) }; public Form1() { Text = "Drag a row"; ClientSize = new Size(360, 160); _source.Items.AddRange(new object[] { "one", "two", "three" }); _source.MouseDown += (sender, e) => { if (_source.SelectedItem is not string text) { return; } var result = _source.DoDragDrop(text, DragDropEffects.Move | DragDropEffects.Copy); if (result == DragDropEffects.Move) { _source.Items.Remove(text); } }; Controls.Add(_source); } }

That block is a fragment: a form with no Main, so the checker counts it and does not build it. DoDragDrop blocks until the drag ends and returns the effect the target chose, which is the only way the source learns what happened. A source that calls it from MouseDown starts the drag on the press; a source that waits for the pointer to move a few pixels first lets a click still be a click.

The clipboard

The clipboard is the same data with a different life: one object at a time, shared by every application. The Clipboard class is static and needs a single-threaded apartment, which a WinForms program already has:

A clipboard call can throw ExternalException when another application holds the clipboard open; the documented answer is to try again, which a paste handler does with a short loop or with the Clipboard calls wrapped in a try. The clipboard is also a global resource: a test that writes to it changes what the user has copied, which is why this course keeps its clipboard listings compile-only.

A drop target that runs

The decision a drop target makes is a lookup over the formats and a filter over the names, and that part runs here:

using System; using System.Collections.Generic; using System.IO; using System.Linq; var payload = new Dictionary<string, object> { ["FileDrop"] = new[] { "C:/notes/a.txt", "C:/notes/b.txt" }, ["Text"] = "C:/notes/a.txt", }; foreach (var format in payload.Keys) { Console.WriteLine($"format: {format}"); } var files = (string[])payload["FileDrop"]; Console.WriteLine($"names: {string.Join(", ", files.Select(Path.GetFileName))}"); Console.WriteLine($"accepts: {Accepts(files)}"); Console.WriteLine($"effect: {Effect(payload)}"); static bool Accepts(string[] names) => names.Length > 0 && names.All(name => Path.GetExtension(name).Equals(".txt", StringComparison.OrdinalIgnoreCase)); static string Effect(Dictionary<string, object> data) => data.ContainsKey("FileDrop") ? "Copy" : data.ContainsKey("Text") ? "Move" : "None";

dotnet run

format: FileDrop
format: Text
names: a.txt, b.txt
accepts: True
effect: Copy

The output is the real run. The object holds two formats and the target reads the one it can use, which is exactly what GetDataPresent and GetData do. The filter decides whether the drop is welcome at all, and a target that refuses it returns DragDropEffects.None in DragEnter so the user sees the refusal before releasing the button. The names come from Path.GetFileName, which is the call a drop handler makes before it shows a file in a list.

Exercises

  1. Add a third name with the extension .PNG and explain what accepts prints.
  2. Make Effect prefer Text when both formats are present, and run the program again.
  3. Write the DragEnter handler of a target that accepts only .txt files, in four lines.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which property makes a control a drop target?

    Answer

    AllowDrop = true

    Without it the control receives no drag events and the pointer shows the no-drop cursor.

  2. Which method starts a drag on the source?

    Answer

    DoDragDrop

    It blocks until the drag ends and returns the effect the target chose.

  3. What does e.Effect = DragDropEffects.None in DragEnter mean?

    Answer

    This target refuses the data, so the drop never happens

    The user sees the refusal before releasing the button.

  4. What does DataFormats.FileDrop hold?

    Answer

    A string array of full paths

    It is the format Explorer puts on the object when files are dragged.

  5. What does DoDragDrop return?

    Answer

    The DragDropEffects the target chose

    It is how a source knows whether to remove the row it dragged.

  6. Which call reads the text on the clipboard?

    Answer

    Clipboard.GetText()

    ContainsText is the check before it.

  7. Why does the Clipboard class need a single-threaded apartment?

    Answer

    It uses OLE, which requires one

    A WinForms program has one because of [STAThread] on Main.

  8. What did the run print for the names?

    Answer

    a.txt, b.txt

    Path.GetFileName takes the last segment of each path.

  9. Which event can refuse a drop before the user releases the button?

    Answer

    DragEnter, by setting e.Effect

    The cursor follows the effect of DragEnter and DragOver.

  10. When is DataFormats.Serializable the wrong choice?

    Answer

    Across two different applications

    The other application does not know your type, so it cannot read it.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev