Is it possible to log message to cmd.exe in C#/.Net?

后端 未结 5 2100
别跟我提以往
别跟我提以往 2021-01-05 19:19

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:

pri         


        
5条回答
  •  北海茫月
    2021-01-05 19:45

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

    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();
              }
        }
    

提交回复
热议问题