diff --git a/grr/ConsoleExtensions.cs b/grr/ConsoleExtensions.cs
index a6f20b71..78aa4514 100644
--- a/grr/ConsoleExtensions.cs
+++ b/grr/ConsoleExtensions.cs
@@ -47,6 +47,27 @@ public static Process GetParentProcess(int id)
}
///
+ /// Climbs up the process tree to find the windowed process where SendKey can send the command keys to
+ ///
+ /// The process id
+ /// First parent in the process tree with window handle
+ internal static Process GetWindowedParentProcess(in int id)
+ {
+ var process = Process.GetProcessById(id);
+ while ( process.MainWindowHandle == IntPtr.Zero )
+ {
+ var lastProcess = process;
+ process = GetParentProcess(process.Handle);
+ if ( lastProcess == process )
+ {
+ // Better a result without window handle than an infinite loop
+ break;
+ }
+ }
+ return process;
+ }
+
+ ///
/// Gets the parent process of a specified process.
///
/// The process handle.
@@ -68,27 +89,14 @@ public static Process GetParentProcess(IntPtr handle)
return null;
}
}
- }
+ }
public static void WriteConsoleInput(Process target, string value, int waitMilliseconds = 0)
{
- PrintDebug($"Write to console process {target.ProcessName} ({target.Id})");
-
- if (target.Id == Process.GetCurrentProcess().Id)
- {
- target = ParentProcessUtilities.GetParentProcess(target.Id);
- if (target == null)
- return;
-
- PrintDebug($"Process was grr, took parent {target.ProcessName} ({target.Id})");
- }
-
- var parentProcess = ParentProcessUtilities.GetParentProcess(target.Id);
- if (parentProcess?.ProcessName.Equals("WindowsTerminal", StringComparison.OrdinalIgnoreCase) ?? false)
- {
- target = parentProcess;
- PrintDebug($"Parent process was WindowsTerminal, taking this one to send keys: {parentProcess?.ProcessName ?? ""} ({parentProcess?.Id ?? -1})");
- }
+ // Find the first process in the process tree which has a windows handle
+ target = ParentProcessUtilities.GetWindowedParentProcess(target.Id);
+
+ PrintDebug($"Write to console process {target.ProcessName} ({target.Id})");
// send CTRL+V with Enter to insert the command
var arguments = ("^v{Enter}");