加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何回显现有的CMD窗口

发布时间:2020-12-15 07:57:19 所属栏目:百科 来源:网络整理
导读:所以我正在使用的程序可以使用以下代码在CMD中使用命令行启动. string[] commandLines = Environment.GetCommandLineArgs(); 但是我希望能够在处理命令行之后将消息返回到CMD窗口.任何帮助,将不胜感激. 编辑:我将程序作为Windows应用程序运行,而不是控制台
所以我正在使用的程序可以使用以下代码在CMD中使用命令行启动.
string[] commandLines = Environment.GetCommandLineArgs();

但是我希望能够在处理命令行之后将消息返回到CMD窗口.任何帮助,将不胜感激.

编辑:我将程序作为Windows应用程序运行,而不是控制台应用程序.

解决方法

我最后使用RenniePet发布的答案作为对我的问题的评论来解决问题.我会在这里列出解决方案,以便任何试图重现它的人.
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);

private const int ATTACH_PARENT_PROCESS = -1;

StreamWriter _stdOutWriter;

// this must be called early in the program
public void GUIConsoleWriter()
{
    // this needs to happen before attachconsole.
    // If the output is not redirected we still get a valid stream but it doesn't appear to write anywhere
    // I guess it probably does write somewhere,but nowhere I can find out about
    var stdout = Console.OpenStandardOutput();
    _stdOutWriter = new StreamWriter(stdout);
    _stdOutWriter.AutoFlush = true;

    AttachConsole(ATTACH_PARENT_PROCESS);
}

public void WriteLine(string line)
{
    GUIConsoleWriter();
    _stdOutWriter.WriteLine(line);
    Console.WriteLine(line);
}

将此代码添加到程序后,您只需使用例如以下内容开始返回行.

WriteLine("nExecuting commands.");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读