3
3

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.

Delphiでドラッグ&ドロップを受け付ける方法

Posted at

テスト投稿を兼ねて。

1.usesの追加

uses
  ShellAPI, ActnList;

2.FormCreateなどで受け付け

procedure Sample.FormCreate(Sender: TObject);
begin
  DragAcceptFiles(Handle, true);
end;

3.ドラッグ&ドロップ用メソッドの実装

procedure Sample.WMDropFiles(var msg: TWMDROPFILES);
var
  DropCount: Integer;
  DropFile: Integer;
  pFileName: PChar;
begin
  try
    DropCount := DragQueryFile(msg.Drop, $ffffffff, nil, 0);
    if DropCount  <> 1 then begin
      MessageDlg('ファイルは1つずつドラッグしてください。', mtWarning, [mbOk], 0);
      end;
    end;
    //ドロップされたファイル名のサイズを取得
    DropFile:= DragQueryFile(msg.Drop, 0, nil, 0) + 1;
    //pFilenameに上で得たサイズ分のメモリを確保
    pFileName := AllocMem(DropFile);
    try
      //pFilenameにファイル名を取得
      DragQueryFile(msg.Drop, 0, pFilename, DropFile);
      //後はファイル名を使って読み込むなりなんなり
      LoadCSV(pFileName);
    finally
      //メモリ開放
      FreeMem(pFilename);
    end;
  finally
    //処理の終了をOSに通知
    DragFinish(msg.Drop);
  end;
end;

上記はファイルを1つだけドラッグ&ドロップする場合だが、

for idx := 0 to DropCount-1 do begin
  DropFile:= DragQueryFile(msg.Drop, idx, nil, 0) + 1;
  DragQueryFile(msg.Drop, idx, pFilename, DropFile);
end;

とすれば複数ファイルも受け付けられる。

3
3
1

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?