使用 AttachConsole,当我附加的进程正在运行和喷出时,我仍然可以键入和运行其他命令。
我的程序以表单或命令行运行。如果以参数启动,它将在命令窗口中运行。我使用 AttachConsole(-1) 将我的进程附加到我从中调用的命令窗口。 它工作得很好,我从我的过程中得到了所有的输出。
但是,控制台仍然处理来自键盘的用户输入,无论我键入什么,例如,如果我键入“cls”并按回车键,输出将被删除。如何在进程运行时阻止用户向控制台输入?
最佳答案
根据您正在做的事情,这可能并不优雅,但是在附加它之后在控制台上执行 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());
}
}
}
关于c# - 使用 AttachConsole,当我附加的进程正在运行和喷出时,我仍然可以键入和运行其他命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5629393/