Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 26 additions & 18 deletions grr/ConsoleExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,27 @@ public static Process GetParentProcess(int id)
}

/// <summary>
/// Climbs up the process tree to find the windowed process where SendKey can send the command keys to
/// </summary>
/// <param name="id">The process id</param>
/// <returns>First parent in the process tree with window handle </returns>
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;
}

/// <summary>
/// Gets the parent process of a specified process.
/// </summary>
/// <param name="handle">The process handle.</param>
Expand All @@ -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}");
Expand Down