// injectDll.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Windows.h> #include <Shlwapi.h> int _tmain(int argc, _TCHAR* argv[]) { //获取要注入的dll路径,我这里是放在本模块同一个路径下 TCHAR szDllPath[MAX_PATH] = { 0 }; ::GetModuleFileName(NULL, szDllPath, MAX_PATH); ::PathRemoveFileSpec(szDllPath); _tcscat(szDllPath, _T("//taskDll.dll")); //找到窗口对应的进程并且打开,这里是打开了exeplorer.exe HWND hWnd = ::FindWindow(_T("Shell_TrayWnd"), NULL); DWORD dwProcessId = 0; ::GetWindowThreadProcessId(hWnd, &dwProcessId); HANDLE hProcess = ::OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, FALSE, dwProcessId); //在外部进程中分配虚拟地址空间并把dll路径名放进去 DWORD dwSize = (_tcslen(szDllPath) + 1) * sizeof(TCHAR); DWORD dwWrite = 0; LPVOID lpDllPath = ::VirtualAllocEx(hProcess, 0, dwSize, MEM_COMMIT, PAGE_READWRITE); ::WriteProcessMemory(hProcess, lpDllPath, (LPVOID)szDllPath, dwSize, &dwWrite); //在外部进程中创建线程,其中线程函数为LoadLibraryW,参数就是dll路径名所在的地址 LPVOID pFunc = LoadLibraryW; DWORD dwId = 0; HANDLE hThread = ::CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pFunc, lpDllPath, 0, &dwId); //等待线程执行完毕 ::WaitForSingleObject(hThread, INFINITE); //释放用于放置dll路径名的虚拟地址空间 ::VirtualFreeEx(hProcess, lpDllPath, dwSize, MEM_DECOMMIT); ::CloseHandle(hThread); ::CloseHandle(hProcess); /* LoadLibraryW执行的时候会执行dll初始化代码,你想干的事就可以在dll的初始化代码中做了 比如替换窗口过程,启动进程等等 注意: 为了简洁,我这里对API调用成功与否的判断都忽略了,实际应用中是要做处理的 */ return 0; }