【问题标题】:Using AttachConsole, while the process I've attached with is running and spewing, I can still type and run other commands使用 AttachConsole,虽然我附加的进程正在运行和喷涌,但我仍然可以键入和运行其他命令
【发布时间】:2011-08-03 12:25:12
【问题描述】:
使用 AttachConsole,虽然我附加的进程正在运行和喷涌,但我仍然可以键入和运行其他命令。
我的程序以表单或命令行运行。如果从参数开始,它将在命令窗口中运行。我使用 AttachConsole(-1) 将我的进程附加到我调用的命令窗口。
效果很好,我的所有输出都来自我的流程。
但是,无论我键入什么,控制台仍会处理来自键盘的用户输入,例如,如果我键入“cls”并按 Enter,则输出将被擦除。如何在进程运行时阻止用户输入到控制台?
【问题讨论】:
标签:
c#
.net
console
console-application
【解决方案1】:
根据您正在做的事情,这可能并不优雅,但是在附加它之后在控制台上执行 Kill() ,它将继续从您的其他进程获取输出。下面的示例 Windows 窗体代码,添加您自己的花里胡哨:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
internal static class Program
{
[DllImport("kernel32", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
[STAThread]
private static void Main(string[] args)
{
IntPtr ptr = GetForegroundWindow();
int u;
GetWindowThreadProcessId(ptr, out u);
Process process = Process.GetProcessById(u);
AttachConsole(process.Id);
process.Kill();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
【解决方案2】:
我发现一个更简洁的解决方案是在程序退出后向控制台发送一个额外的“Enter”:
[STAThread]
public static int Main(string[] args)
{
try
{
AttachConsole(ATTACH_PARENT_PROCESS);
...
...
}
catch (Exception eCatchAll)
{
ShowHelpCommand.ShowHelp(eCatchAll.ToString());
return (int) ConsoleReturnCode.UnexpectedError;
}
finally
{
ConsoleNewLine();
}
}
private static void ConsoleNewLine()
{
try
{
// When using a winforms app with AttachConsole the app complets but there is no newline after the process stops. This gives the newline and looks normal from the console:
SendKeys.SendWait("{ENTER}");
}
catch (Exception e)
{
Debug.Fail(e.ToString());
}
}
【解决方案3】:
对此不太确定,但 AllocConsole 而不是 AttachConsole 不是解决此问题的更简单方法吗?