1. 程式人生 > >c++ 發送消息,模擬拖拽文件

c++ 發送消息,模擬拖拽文件

byte dwr ems bre param strcpy rem code filepath

 1 #include <ShlObj.h>
 2 BOOL SimulateDropFile(CString strFilePath)
 3 {
 4     char szFile[MAX_PATH] = {0};
 5     wcstombs(szFile, strFilePath.GetBuffer(0), _MAX_PATH);
 6     DWORD dwBufSize = sizeof(DROPFILES) + strlen(szFile) + 1;
 7     
 8     //通過類名或窗口標題 找到接受拖拽的窗口
 9     HWND hMain = ::FindWindow(NULL, _T("
XX播放器")); 10 if (hMain == NULL) 11 return FALSE; 12 BYTE* pBuf = new BYTE[dwBufSize]; 13 if (pBuf == NULL) 14 return FALSE; 15 16 BOOL bResult = FALSE; 17 memset(pBuf, 0, dwBufSize); 18 DROPFILES* pDrop = (DROPFILES*)pBuf; 19 pDrop->pFiles = sizeof(DROPFILES);
20 strcpy((char*)(pBuf + sizeof(DROPFILES)), szFile); 21 22 DWORD dwProcessId = 0; 23 GetWindowThreadProcessId(hMain, &dwProcessId); 24 if (dwProcessId != NULL) 25 { 26 HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE, FALSE, dwProcessId); 27 if
(hProcess != NULL) 28 { 29 LPSTR pszRemote = (LPSTR)VirtualAllocEx(hProcess, NULL, dwBufSize, MEM_COMMIT, PAGE_READWRITE); 30 if (pszRemote && WriteProcessMemory(hProcess, pszRemote, pBuf, dwBufSize, 0)) 31 { 32 ::SendMessage(hMain, WM_DROPFILES, (WPARAM)pszRemote, NULL); 33 bResult = TRUE; 34 } 35 } 36 } 37 38 if (pBuf) 39 { 40 delete[] pBuf; 41 pBuf = NULL; 42 } 43 return bResult; 44 }

在調用該函數之前,先打開接受拖拽的進程
ShellExecute(NULL, L"open", exe完整路徑, NULL, NULL, SW_SHOWNORMAL);

c++ 發送消息,模擬拖拽文件