It doesn't work because your code is for x86 while by calculator (calc.exe) is x86_64 by default. Try it on some other process that has a *32 in task manager (x86 program) and it should work. Some evidence:
This is my code (thanks to Darawk) but before you try my code try yours on an x86 program:
Code:
#include <cstdio>
#include <Windows.h>
#include <TlHelp32.h>
#include <string>
using std::string;
using std::wstring;
#define PROCESS_NAME L"Swag.exe"
#define MODULE_NAME "C:\\Users\\Swag\\Desktop\\Dll.dll"
int wmain()
{
// Get a snapshot and then filter for getting
// the Id of the process we want
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hSnapshot == INVALID_HANDLE_VALUE)
{
printf_s("Error: Could not get snapshot (Code: %i)\n", GetLastError());
return S_FALSE;
}
// Iterate 'snapshotted' processes for the one
// we want
PROCESSENTRY32 pe32 = { };
pe32.dwSize = sizeof(PROCESSENTRY32);
if(!Process32First(hSnapshot, &pe32))
{
printf_s("Error: Process32First returned false (Code: %i)\n", GetLastError());
CloseHandle(hSnapshot);
return S_FALSE;
}
bool foundProcess = false;
do
{
if(std::wstring(pe32.szExeFile) == PROCESS_NAME)
{
foundProcess = true;
break; // Found the process we want
}
} while(Process32Next(hSnapshot, &pe32));
if(!foundProcess)
{
printf_s("Error: Failed to find process (Code: %i)\n", GetLastError());
CloseHandle(hSnapshot);
return S_FALSE;
}
// Get the Id of the process and use it
// to inject the module into the process
DWORD procId = pe32.th32ProcessID;
HANDLE hProcess = OpenProcess(((PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ)), FALSE, procId);
if(hProcess == NULL)
{
printf_s("Error: Failed to open process (Code: %i)\n", GetLastError());
CloseHandle(hSnapshot);
return S_FALSE;
}
auto addrOfLoadLibrary = GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryA");
auto remoteAlloc = VirtualAllocEx(hProcess, NULL, strlen(MODULE_NAME), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if(WriteProcessMemory(hProcess, remoteAlloc, MODULE_NAME, strlen(MODULE_NAME), NULL) == 0)
{
printf_s("Error: Failed to write to process' memory (Code: %i)\n", GetLastError());
CloseHandle(hProcess);
CloseHandle(hSnapshot);
return S_FALSE;
}
if(CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE) addrOfLoadLibrary, remoteAlloc, NULL, NULL) == NULL)
{
printf_s("Error: Failed to create remote thread (Code: %i)\n", GetLastError());
CloseHandle(hProcess);
CloseHandle(hSnapshot);
return S_FALSE;
}
printf_s("Finished Successfully!\n");
// Clean up a bit
CloseHandle(hSnapshot);
CloseHandle(hProcess);
return S_OK;
}