如何類比檔案拖拽,這個問題得反過來分析:“如何接受檔案拖拽”?
分別要用到API:
DragAcceptFiles()函數,令表單接受檔案拖拽的訊息
WM_DROPFILES訊息檔案拖拽時接收
看來得向表單發送WM_DROPFILES訊息,發送訊息是SendMessage()函數
為節約時間我們要站在巨人的肩膀--搜尋
關鍵詞就基本確定為:“WM_DROPFILES SendMessage 類比檔案拖拽”
此處省略1000字
uses ShlObj;
function ExecDropFile( // 類比檔案拖拽
AHandle: THandle; // 目標表單控制代碼
AFileName: string // 檔案名稱
): Boolean; // 返回執行是否成功
var
vDropFiles: TDropFiles;
vProcessId: DWORD;
vProcess: THandle;
vPointer: PChar;
vNumberOfBytesRead: Cardinal;
begin
Result := False;
if not FileExists(AFileName) or not IsWindow(AHandle) then Exit;
GetWindowThreadProcessId(AHandle, @vProcessId);
vProcess := OpenProcess(PROCESS_VM_OPERATION or PROCESS_VM_READ or
PROCESS_VM_WRITE, False, vProcessId);
try
vPointer := VirtualAllocEx(vProcess, nil, 4096, MEM_RESERVE or MEM_COMMIT,
PAGE_READWRITE);
try
FillChar(vDropFiles, SizeOf(vDropFiles), 0);
vDropFiles.pFiles := SizeOf(TDropFiles);
WriteProcessMemory(vProcess, vPointer,
@vDropFiles, SizeOf(vDropFiles), vNumberOfBytesRead);
WriteProcessMemory(vProcess, vPointer + SizeOf(vDropFiles),
PChar(AFileName), Length(AFileName) + 1, vNumberOfBytesRead);
SendMessage(AHandle, WM_DROPFILES, Integer(vPointer), 0);
finally
VirtualFreeEx(vProcess, vPointer, 0, MEM_RELEASE);
end;
finally
CloseHandle(vProcess);
end;
Result := True;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ExecDropFile(FindWindow('Notepad', nil), 'c:/temp/temp.txt');
end;