p
is null because
Process.GetProcessesByName
expects the "friendly name" of a process, not the full file path that appears to be returned by GetActiveProcessFileName.
But here's some good news: you don't even need to use GetProcessesByName to get the process you want: in GetActiveProcessFileName, you have a line
Process p = Process.GetProcessById((int)pid)
and this
p
is exactly the process you wish, so you don't need to return this process's file name to retrieve the Process again later: just return
p
already. Here is a
GetActiveProcess
method that returns the desired process:
static Process GetActiveProcess()
{
IntPtr hwnd = GetForegroundWindow();
uint pid;
GetWindowThreadProcessId(hwnd, out pid);
return Process.GetProcessById((int)pid);
}
And then you can replace the
Process p = Process.GetProcessesByName ...
line with this:
Process p = GetActiveProcess();
[Edit]
It appears that
"^C"
doesn't always make the active application copy the selected text, but I've had better results with
"^c"
(that is, a lowercase c).