2

私はユーティリティ(http://reg2run.sf.net)を作成しています。これは、引数なしで実行するとWindowsアプリケーション(OpenFileDialogなどを表示)として機能し、そうでない場合はコンソールアプリケーションとして機能します。

したがって、最初のケースでは、コンソール ウィンドウを表示したくないため、プロジェクトは Windows アプリケーションです。しかし、2番目に-表示する必要があり、それはで作成されています

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);

そして、私が望むのは、親プロセスの標準出力を取得して、存在する場合はそれを使用することです(cmd.exeまたはFar Managerを介して実行する場合)。どうすればいいですか?

私は試した

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;
}

StreamWriter newOut = GetParentProc().StandardInput;

しかし、InvalidOperationException: StandardIn はリダイレクトされていません。なぜなら

GetParentProc().StartInfo.RedirectStandardOutput = false
4

2 に答える 2

3

いつでも次の P/Invoke メソッドを使用できます。

[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);

const int ATTACH_PARENT_PROCESS = -1;
于 2008-12-18T17:41:45.270 に答える