是否有可能日志消息cmd.exe,在C#/。NET? [英] Is it possible to log message to cmd.exe in C#/.Net?

查看:221
本文介绍了是否有可能日志消息cmd.exe,在C#/。NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能登陆的WinForms应用程序消息的cmd.exe进程启动编程?我试着做各种以下code变化:

Is it possible to log message from WinForms app to cmd.exe process started programmatically? I've tried to do all kinds of variations of following code:

private void button1_Click(object sender, EventArgs e)
{
    Log("Button has been pressed");
}

private void Log(string message)
{
    var process = Process.Start(new ProcessStartInfo("cmd.exe", @"/K ""more""")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
    });
    process.StandardInput.WriteLine(message);
}

不幸的是,控制台窗口闪烁的第二个一半,仅此而已。

Unfortunately, console window blinks for a half of a second and that's it.

请不要回答我真正想做的事情,因为现在我是否有可能只是好奇:)

Please don't answer what I really want to do, because right now I'm just curious if it's possible :)

推荐答案

您很幸运。我只是解决了这个为code发电机玩具项目,我已经漂浮在这里。

You're in luck. I just solved this for a code generator toy project I had floating around here.

使用 AttachConsole AllocConsole 的Win32 API的可以实现的结果,仅仅使用的System.Console.WriteLine (或阅读,或Error.WriteLine等),就像你通常会。

Using AttachConsole or AllocConsole Win32 API's you can achieve the result, by just using System.Console.WriteLine (or Read, or Error.WriteLine etc) like you normally would.

下面的代码片段计算出,当窗体应用程序从一个控制台窗口中启动,并连接到它的父控制台;如果还是不行,它会创建自己的控制台,记得要保持开放的(所以它不会消​​失之前,用户可以阅读的输出,例如)。

The following snippet figures out when a forms app was started from a Console window, and attaches to it's parent console; If that doesn't work, it will create it's own console, and remember to keep it open (so it doesn't vanish before the user can read the output, for example).

    [DllImport("kernel32.dll")] static extern bool AllocConsole();
    [DllImport("kernel32.dll")] static extern bool AttachConsole(int pw);
    private static bool _hasConsole, _keepConsoleOpen;
    static private void EnsureConsole()
    {
        _hasConsole      =  _hasConsole || AttachConsole(-1);
        _keepConsoleOpen = !_hasConsole || _keepConsoleOpen;
        _hasConsole      =  _hasConsole || AllocConsole();
    }

    [STAThread]
    private static void Main(string[] args)
    {
          EnsureConsole();

          // the usual stuff -- your program

          if (_keepConsoleOpen)
          {
              Console.WriteLine("(press enter)...");
              Console.Read();
          }
    }

这篇关于是否有可能日志消息cmd.exe,在C#/。NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆