C# 忘備録 formにドラック&ドロップしてファイルパスをlistBoxに取得する
エクスプローラーのファイルをformにドラック&ドロップしてファイルパスをlistBoxに入れる処理
まずはリストボックスを配置する
listboxのプロパティからAllowDropをTrueにする
コードを開いてドラッグ時のコードを書き込む
//ドラッグイベントの処理
private void ListBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
//formに入っている場合の動作
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
//ドロップした場合のエフェクト
e.Effect = DragDropEffects.All;
}
else
{
//ドロップがなかった場合のエフェクト
e.Effect = DragDropEffects.None;
}
}
さらにドロップ時のコードを書き込む
//ドロップ時の操作
private void ListBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
//ファイルパスを取得してStringに入れる
string[] pass = (string[])e.Data.GetData(DataFormats.FileDrop, false);
for (int i = 0; i < pass.Length; i++)
{
//パスの中身(ファイルパス)をリストボックスに入れる(複数可)
listBox1.Items.Add(pass[i]);
}
}
次に忘れてはいけないのがデザイナーの設定 listBoxの下に追加します
this.listBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.ListBox1_DragDrop);
this.listBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.ListBox1_DragEnter);
コードは以上
起動します。
適当にファイルを作ってドラック&ドロップします
複数同時もいけます。
以上!
コメント
コメントを投稿