11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

エクスプローラからドラッグ&ドロップされたファイルパスを取得する

Last updated at Posted at 2012-05-22

C# で作成したフォームアプリケーションに、
エクスプローラからドロップされたファイルパスを取得する機能を付加するには、
例えばフォームに配置したlistBox1に対して以下の実装を行えば良い。

  1. AllowDrop プロパティを true に設定する
  2. DragEnter イベントハンドラを実装し、ドラッグドロップを受け付けることを表明する
  3. DragDrop イベントハンドラを実装し、ドラッグドロップされたファイルパスを受け取って処理する
SampleDragDrop.cs
        void MainForm_Load(object sender, EventArgs e)
        {
            // ドラッグドロップを受け付ける
            listBox1.AllowDrop = true;
        }
        
        void ListBox1_DragEnter(object sender, DragEventArgs e)
        {
            // ドラッグドロップ時にカーソルの形状を変更
            e.Effect = DragDropEffects.All;
        }

        void ListBox1_DragDrop(object sender, DragEventArgs e)
        {
            // ファイルが渡されていなければ、何もしない
            if ( ! e.Data.GetDataPresent(DataFormats.FileDrop)) return;
            
            // 渡されたファイルに対して処理を行う
            foreach (var filePath in (string[])e.Data.GetData(DataFormats.FileDrop)) {
                listBox1.Items.Add(filePath);
            }
        }
11
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?