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

标签 c# .net console console-application

使用 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/

相关文章:

c# - 在 watch/debugger 中查看 LINQ 查询的结果

c# - 声明类型为 "emails",然后 ClaimTypes.Email 为 null

.net - 如何使用 Visual Studio 2008 单元测试避免重复的 app.config?

delphi - Delphi 中用于命令提示符的管道

c# - 字符串、对象和整数之间的转换和解析

c# - 如果未找到匹配项,则 FirstOrDefault 返回 NullReferenceException

c# - Xamarin - 找不到元数据文件 .../AWSSDK.SecurityToken.CodeAnalysis.dll

c# - vs 2012 中烦人的 log4net assembly 引用问题

c# - C# .NET 控制台应用程序使用的控制台字体和布局

console - 处理隐藏控制台警告