#include "ProcessInjector.h"

#include <psapi.h>
#include <stdio.h>

int PrintProcessNameAndID(DWORD processID, const char *name)
{
	CHAR szProcessName[MAX_PATH] = "<unknown>";

	// Get a handle to the process.

	HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
		PROCESS_VM_READ,
		FALSE, processID);

	// Get the process name.

	if (NULL != hProcess)
	{
		HMODULE hMod;
		DWORD cbNeeded;

		if (EnumProcessModules(hProcess, &hMod, sizeof(hMod),
			&cbNeeded))
		{
			GetModuleBaseNameA(hProcess, hMod, szProcessName,
				sizeof(szProcessName) / sizeof(TCHAR));
		}
	}


	if (strcmp(szProcessName, name) == 0) // right process
	{
		CloseHandle(hProcess);
		return 1;
	}

	// Release the handle to the process.

	CloseHandle(hProcess);
	return 0;
}

int find(const char *name)
{
	// Get the list of process identifiers.

	DWORD aProcesses[1024], cbNeeded, cProcesses;
	unsigned int i;

	if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
	{
		return 0;
	}


	// Calculate how many process identifiers were returned.

	cProcesses = cbNeeded / sizeof(DWORD);

	// Print the name and process identifier for each process.

	for (i = 0; i < cProcesses; i++)
	{
		if (aProcesses[i] != 0)
		{
			if (PrintProcessNameAndID(aProcesses[i], name))
			{
				//found it
				printf("%d %s\n", aProcesses[i], name);
				return aProcesses[i];
			}
		}
	}
	return 0;
}

void main()
{
	DWORD dwProcessId = find("notepad.exe");

	if (dwProcessId != 0)
	{
		PINJECT_PROCESS_PARAMETERS params = malloc(sizeof(INJECT_PROCESS_PARAMETERS));
		SecureZeroMemory(params, sizeof(INJECT_PROCESS_PARAMETERS));
		params->dwProcessId = dwProcessId;

		//HANDLE hThread = InjectProcess(params);
		CreateThread(NULL, 0, InjectProcess, params, 0, NULL);
		//WaitForSingleObject(hThread, INFINITE);
		Sleep(INFINITE);
	}

}