1

Hey guys I can't seem to get my code to work the way I want it. I am waiting for a process to start, AKA show up in my Task Manager. While the process is not found, I keep looping; if process is found then break while loop and perform logic below AKA inject DLL. I have break points in but my code just keeps looping so its like the process is never found although it is showing in task manager.

public static int inject(string dllPath, Process tProcess)
{
  Process targetProcess = tProcess;
  string dllName = dllPath;
  const string PROCESSNAME = "BatteryLife.exe";
  // Length == 0 = False?
   while (Process.GetProcessesByName(PROCESSNAME).Length == 0)
   {
     var test3 = "";
     Thread.Sleep(100);
     // Length == 1 = True?
     if (Process.GetProcessesByName(PROCESSNAME).Length == 1)
      break;
     var test = "";
   }
   var test2 = "";
   // the target process
   // geting the handle of the process - with required privileges
   IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD |   PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, targetProcess.Id);
  // searching for the address of LoadLibraryA and storing it in a pointer
  IntPtr loadLibraryAddr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
  // name of the dll we want to inject
  // alocating some memory on the target process - enough to store the name of the dll
  // and storing its address in a pointer
  IntPtr allocMemAddress = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((dllName.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
  // writing the name of the dll there
  UIntPtr bytesWritten;
  WriteProcessMemory(procHandle, allocMemAddress,    Encoding.Default.GetBytes(dllName), (uint)((dllName.Length + 1) *  Marshal.SizeOf(typeof(char))), out bytesWritten);
 // creating a thread that will call LoadLibraryA with allocMemAddress as argument
  CreateRemoteThread(procHandle, IntPtr.Zero, 0, loadLibraryAddr, allocMemAddress, 0, IntPtr.Zero);
  return 0;
}
SanyTiger
  • 666
  • 1
  • 8
  • 23
Doobie2012
  • 66
  • 8
  • 2
    Is the PROCESSNAME actually "BatteryLife.exe" and not just "BatteryLife"? – Daniel Centore Feb 24 '16 at 04:43
  • Possible duplicate of [How can I know if a process is running?](http://stackoverflow.com/questions/262280/how-can-i-know-if-a-process-is-running) – Gabe Feb 24 '16 at 04:55

1 Answers1

1

I think you need to remove the .exe from the process name string.

Process[] pname = Process.GetProcessesByName("BatteryLife");
if (pname.Length == 0)
{
  .....
}
SanyTiger
  • 666
  • 1
  • 8
  • 23
Olivarsham
  • 1,701
  • 5
  • 25
  • 51
  • 1
    Just to add for the OPs enrichment, take a look at the MSDN docs. Though the description is unclear, the examples show calls without the extension, eg `Process.GetProcessesByName("notepad")` https://msdn.microsoft.com/en-us/library/z3w4xdc9(v=vs.110).aspx – Kevin Burdett Feb 24 '16 at 04:56