エクスプローラーからドラッグ&ドロップに応答(VCL) ~Delphiソースコード集
エクスプローラーからファイルやフォルダをフォームやコントロールにドラッグ&ドロップした時のファイル名を取得する
プロジェクトとフォームの作成
Delphi IDEを起動し、「ファイル」⇒「Windows VCLアプリケーション -Delphi」をクリックしますフォーム上に以下をドラッグ&ドロップします。
TListBox×1個、TMemo×1個、TApplicaitonEvents×1個

ソースコードの記述
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.AppEvnts, Vcl.StdCtrls; type TForm1 = class(TForm) ListBox1: TListBox; Memo1: TMemo; ApplicationEvents1: TApplicationEvents; procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); procedure FormCreate(Sender: TObject); private { Private 宣言 } public { Public 宣言 } end; var Form1: TForm1; implementation {$R *.dfm} uses Winapi.ShellAPI; procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); var DropCount:Cardinal; i:Cardinal; FileName:array[0..4096] of Char; p:TPoint; begin Handled:=False; if Msg.message=WM_DROPFILES then begin //ドロップされた座標を取得(フォーム又はコントロール上での座標) DragQueryPoint(Msg.wParam,p); Memo1.Lines.Add('座標:'+Format('%d,%d',[p.X,p.Y])); //ドロップされたコントロールを表示 if Msg.hwnd=Form1.Handle then Memo1.Lines.Add('Form1にドロップ') else if Msg.hwnd=ListBox1.Handle then Memo1.Lines.Add('ListBox1にドロップ') else if Msg.hwnd=Memo1.Handle then Memo1.Lines.Add('Memo1にドロップ'); try //ドロップされたファイル、フォルダ数を取得 DropCount := DragQueryFile(Msg.wParam, Cardinal(-1), nil, 0); for i := 0 to DropCount-1 do begin DragQueryFile(Msg.wParam, i, FileName, Length(FileName)); // ドロップされたファイル、フォルダをListBox1に表示する ListBox1.Items.Add(FileName); end; finally DragFinish(Msg.wParam); end; end; end; procedure TForm1.FormCreate(Sender: TObject); begin //Form1でファイルのドロップ処理を受け付ける場合 DragAcceptFiles(Self.Handle, True); //ListBox1でドロップ処理を受け付ける場合 DragAcceptFiles(ListBox1.Handle, True); //Memo1でドロップ処理を受け付ける場合 DragAcceptFiles(Memo1.Handle, True); end; end.
実行する
フォーム(ウィンドウ)や、 Memo1やListBox1にファイルやフォルダをドラッグ&ドロップすると、ListBox1にファイルやフォルダが表示されます