【C#】【Form】ドラッグ&ドロップでファイルを開く

■ ドラッグ&ドロップに関するイベント

【1】 DragEnter
【2】 DragOver
【3】 DragDrop
【4】 DragLeave

【1】DragEnterイベント

 * ファイルがコントロールの境界内にドラッグされると発生

【2】DragOverイベント

 * ファイルがコントロールの境界を超えてドラッグされると発生

【3】DragDropイベント

 * ドラッグ&ドロップ操作が完了したときに発生

【4】DragLeaveイベント

 * ファイルをコントロールの境界の外へドラッグされると発生

■ 注意

 * 対象コントロールの「AllowDrop=True」にする必要がある
 => デフォルトは、「AllowDrop=False」

 => PictureBoxについては、デザイナーに、AllowDropプロパティが表示されない(あるにはある)
  => コードから設定する


■ サンプル

例1:TextboxにDrag&Drop

コントロール構成
 * Textbox x 2
  => AllowDrop=True ★☆ 重要 ☆★
コード
using System;
using System.Drawing;
using System.Windows.Forms;

namespace SampleForm
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void textBox1_DragDrop(object sender, DragEventArgs e)
    {
      var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
      if(fileNames.Length == 1)
      {
        this.textBox1.Text = fileNames[0];
      }
      else if (fileNames.Length >= 2)
      {
        this.textBox1.Text = fileNames[0];
        this.textBox2.Text = fileNames[1];
      }
    }

    private void textBox1_DragEnter(object sender, DragEventArgs e)
    {
      if (e.Data.GetDataPresent(DataFormats.FileDrop))
      {

        // ドラッグ中のファイルやディレクトリの取得
        string[] drags = (string[])e.Data.GetData(DataFormats.FileDrop);

        foreach (string d in drags)
        {
          if (!System.IO.File.Exists(d))
          {
            // ファイル以外であればイベント・ハンドラを抜ける
            return;
          }
        }
        e.Effect = DragDropEffects.Copy;
      }
    }
  }
}

例2:PictureBoxにDrag&Drop

コントロール構成
 * Textbox x 1
 * PictureBox x 1
コード
using System;
using System.Drawing;
using System.Windows.Forms;

namespace SampleForm
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      // ★☆ 重要 ☆★
      this.pictureBox1.AllowDrop = true;
    }

    private void pictureBox1_DragDrop(object sender, DragEventArgs e)
    {
      var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
      if (fileNames.Length == 1)
      {
        this.textBox1.Text = fileNames[0];
        this.pictureBox1.ImageLocation = fileNames[0];
      }
    }

    private void pictureBox1_DragEnter(object sender, DragEventArgs e)
    {
      if (e.Data.GetDataPresent(DataFormats.FileDrop))
      {

        // ドラッグ中のファイルやディレクトリの取得
        string[] drags = (string[])e.Data.GetData(DataFormats.FileDrop);

        foreach (string d in drags)
        {
          if (!System.IO.File.Exists(d))
          {
            // ファイル以外であればイベント・ハンドラを抜ける
            return;
          }
        }
        e.Effect = DragDropEffects.Copy;
      }
    }
  }
}