【发布时间】:2010-09-27 12:49:14
【问题描述】:
我正在编写一个实用程序 (http://reg2run.sf.net),以防不带参数的执行作为 Windows 应用程序(显示 OpenFileDialog 等),否则 - 作为控制台应用程序。
所以,在第一种情况下,我不想显示控制台窗口,这就是为什么项目是 Windows 应用程序。 但在第二个 - 我需要展示它,它是用
创建的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
【问题讨论】: