使用AttachConsole,当我附加的进程正在运行并且喷出时,我仍然可以键入并运行其他命令

Mat*_*att 8 .net c# console console-application

使用AttachConsole,当我附加的进程正在运行并且喷出时,我仍然可以键入并运行其他命令.

我的程序可以在表单中运行,也可以从命令行运行.如果以参数启动,它将在命令窗口中运行.我使用AttachConsole(-1)将我的进程附加到我调用的命令窗口.它工作得很好,我从我的过程中得到了所有输出.

但是,控制台仍会处理来自键盘的用户输入,无论我输入什么,例如,如果我输入'cls'并按Enter键,输出将被擦除.如何在进程运行时阻止用户对控制台的输入?

man*_*lds 5

根据你正在做的事情,这可能不是很优雅,但是在附加它之后在控制台上执行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());
    }
}
}
Run Code Online (Sandbox Code Playgroud)