I'm writing an utility (http://reg2run.sf.net) which in case execution without arguments works as windows application (shows OpenFileDialog, etc), otherwise - as console application.
So, in first case I don't want to show a console window, that's why project is Windows Application. But in second - I need to show it, and it's created with
if (ptrNew == IntPtr.Zero)
{
ptrNew = GetStdHandle(-11);
}
if (!AllocConsole())
{
throw new ExternalCallException("AllocConsole");
}
ptrNew = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (!SetStdHandle(-11, ptrNew))
{
throw new ExternalCallException("SetStdHandle");
}
StreamWriter newOut = new StreamWriter(Console.OpenStandardOutput());
newOut.AutoFlush = true;
Console.SetOut(newOut);
Console.SetError(newOut);
And what I want - is to grab parent process standard output and use it, if it exists (in case execution via cmd.exe or Far Manager). How can I do it?
I tried
static Process GetParentProc()
{
int pidParent = 0;
int pidCurrent = Process.GetCurrentProcess().Id;
IntPtr hSnapshot = CreateToolhelp32Snapshot(2, 0);
if (hSnapshot == IntPtr.Zero)
{
return null;
}
PROCESSENTRY32 oProcInfo = new PROCESSENTRY32();
oProcInfo.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32));
if (!Process32First(hSnapshot, ref oProcInfo))
{
return null;
}
do
{
if (pidCurrent == oProcInfo.th32ProcessID)
{
pidParent = (int)oProcInfo.th32ParentProcessID;
}
}
while (pidParent == 0 && Process32Next(hSnapshot, ref oProcInfo));
if (pidParent > 0)
{
return Process.GetProcessById(pidParent);
}
else
{
return null;
}
and
StreamWriter newOut = GetParentProc().StandardInput;
but got InvalidOperationException: StandardIn has not been redirected. Because of
GetParentProc().StartInfo.RedirectStandardOutput = false