I posted this on Stack Overflow, here's the updated version. Still working consistently on getting it working.
Code:
#include <iostream>
#include <windows.h>
#include <TlHelp32.h>
char* dllPath = "C:\\Users\\Kalist\\Desktop\\Projects\\DLL\\bin\\Debug\\DLL.dll";
char* ProcToInject = "calc.exe";
int main(){
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE procSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
DWORD procID = 0;
if(procSnap){
if(Process32First(procSnap, &pe32)){
do{
if(!strcmp(pe32.szExeFile, ProcToInject)){
procID = pe32.th32ProcessID;
break;
}
}while(Process32Next(procSnap, &pe32));
}
CloseHandle(procSnap);
}
HANDLE procAccess = OpenProcess(PROCESS_ALL_ACCESS, false, procID);
LPVOID memSpace = (LPVOID)VirtualAllocEx(procAccess, NULL, strlen(dllPath)+1, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
WriteProcessMemory(procAccess, (LPVOID)memSpace, dllPath, strlen(dllPath)+1, NULL);
LPVOID getLibadd = (LPVOID)GetProcAddress(GetModuleHandle("Kernel32.dll"), "LoadLibraryA");
CreateRemoteThread(procAccess, NULL, 0, (LPTHREAD_START_ROUTINE)getLibadd, (LPVOID)memSpace, 0, NULL);
CloseHandle(procAccess);
}
Code:
#include <windows.h>
BOOL WINAPI DllMain(HINSTANCE hInstDll, DWORD fdwReason, LPVOID lpvReserved)
{
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
MessageBox(NULL, "Process attached", "Message from Dll", MB_OK);
break;
case DLL_THREAD_ATTACH:
MessageBox(NULL, "Thread attached", "Message from Dll", MB_OK);
break;
case DLL_PROCESS_DETACH:
MessageBox(NULL, "Process detached", "Message from Dll", MB_OK);
break;
case DLL_THREAD_DETACH:
MessageBox(NULL, "Thread detached", "Message from Dll", MB_OK);
break;
}
return true;
}
I haven't done your suggestion because I haven't looked into exception handlers and GetError function. But I might be forced to if it continues to refuse working.