フォームにドロップされたファイルを処理する

フォームにドロップされたファイルを処理するには、WM_DROPFILESメッセージのハンドラをフォームに追加します。例えば、次のようにします。
Unit1.h:

//---------------------------------------------------------------------------
class TForm1 : public TForm
{
private:
        // ...
        void __fastcall WMDropFiles(TMessage& AMessage);
        // ...
protected:
public:
        __fastcall TForm1(TComponent* AOwner);
        // ...
        BEGIN_MESSAGE_MAP
                MESSAGE_HANDLER(WM_DROPFILES, TMessage, WMDropFiles)
        END_MESSAGE_MAP(TForm)
        // ...
};
//---------------------------------------------------------------------------

Unit1.cpp:

//---------------------------------------------------------------------------
void __fastcall TForm1::WMDropFiles(TMessage& AMessage)
{
        HDROP dropHandle = reinterpret_cast<HDROP>(AMessage.WParam);
        try {
                SetForegroundWindow(Handle);
                const UINT fileCount = DragQueryFile(dropHandle, 0xFFFFFFFF, NULL, 0);
                const UINT bufferSize = MAX_PATH;
                TCHAR buffer[bufferSize] = {0};
                Memo1->Lines->Add(AnsiString().sprintf("%u files are dropped:", fileCount));
                for(UINT i = 0; i < fileCount; i++) {
                        if(DragQueryFile(dropHandle, i, buffer, bufferSize) > bufferSize) {
                                throw EInvalidOperation("Cannot get the path of a dropped file.");
                        }
                        Memo1->Lines->Add(AnsiString().sprintf("\t%s", buffer));
                }
        }
        __finally {
                DragFinish(dropHandle);
        }
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* AOwner)
{
        DragAcceptFiles(Handle, true);
}
//---------------------------------------------------------------------------
最終更新: 2008-07-10

戻る