private static void MainLoop(Byte[] unicodeDllPath, CancellationTokenSource cts, TimeSpan timeout) { while (true) { cts.Token.ThrowIfCancellationRequested(); try { KeepAlive(cts, timeout); WindowsObject window = WindowsObject.Wait("Debug", InviteMessages, cts.Token, out Int32 messageIndex); if (messageIndex != 0) { window.Close(); KeepAlive(cts, timeout); return; } Int32 processId = window.GetProcessId(); Console.WriteLine(); Console.WriteLine($"A new debuggable process [PID: {processId}] was found. Trying to inject DLL..."); using (SafeProcessHandle processHandle = new SafeProcessHandle(processId, ProcessAccessFlags.All, false)) using (SafeVirtualMemoryHandle memoryHandle = processHandle.Allocate(unicodeDllPath.Length, AllocationType.Commit, MemoryProtection.ReadWrite)) { memoryHandle.Write(unicodeDllPath); // Uncomment to debug // System.Diagnostics.Debugger.Launch(); // KeepAlive(cts, TimeSpan.FromMinutes(10)); IntPtr loadLibraryAddress = GetLoadLibraryAddress(); using (SafeRemoteThread thread = processHandle.CreateThread(loadLibraryAddress, memoryHandle)) { thread.Join(); window.Close(); } } KeepAlive(cts, timeout); Console.WriteLine($"DLL was successfully injected to the process with PID: {processId}."); } catch (OperationCanceledException) { throw; } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Faield to inject DLL."); Console.WriteLine(ex); cts.Token.ThrowIfCancellationRequested(); Console.WriteLine("Waiting 20 seconds to try again..."); Console.WriteLine("Press Ctrl+C to exit..."); Thread.Sleep(20 * 1000); } } }