Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. How to redirect WriteFile func writes to console

How to redirect WriteFile func writes to console

Scheduled Pinned Locked Moved C / C++ / MFC
tutorialquestioncsharpwpfhelp
21 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L leon de boer

    Okay so this spawns the thread before it executes the command passed in. It should spit the console even if the command doesn't terminate, which I still find strange.

    #include
    #include
    #include
    #include

    FILE* OutStream;
    FILE* InStream;
    FILE* ErrStream;

    struct execData {
    TCHAR* CmdLine;
    TCHAR* CmdRunDir;
    PROCESS_INFORMATION process_info;
    STARTUPINFO startup_info;
    };

    struct execData data = { 0 };

    /*---------------------------------------------------------------------------
    Application handler.
    ---------------------------------------------------------------------------*/
    LRESULT CALLBACK GUIDemoHandler (HWND Wnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
    switch (Msg) {
    case WM_CREATE:
    AllocConsole(); //Allocate a console
    freopen_s(&InStream, "CONIN$", "r", stdin); // Redirect standard in
    freopen_s(&OutStream, "CONOUT$", "w", stdout); // Redirect standard out
    freopen_s(&ErrStream, "CONOUT$", "w", stderr); // Redirect standard error
    break;
    case WM_DESTROY: // WM_DESTROY MESSAGE
    if (data.process_info.hProcess) TerminateProcess(data.process_info.hProcess, 0);
    FreeConsole();
    PostQuitMessage(0); // Post quit message
    break;

    	default: return DefWindowProc(Wnd, Msg, wParam, lParam);	// Default handler
    };// end switch case
    return 0;
    

    }

    DWORD WINAPI ExecThreadFunction(LPVOID lpParam)
    {
    int Success;
    struct execData* data = (struct execData*)lpParam;
    Success = CreateProcess(
    nullptr,
    data->CmdLine,
    nullptr,
    nullptr,
    TRUE,
    0,
    nullptr,
    data->CmdRunDir,
    &data->startup_info,
    &data->process_info
    );

    if (!Success) {
    	CloseHandle(data->process\_info.hProcess);
    	CloseHandle(data->process\_info.hThread);
    	return -4;
    }
    else {
    	CloseHandle(data->process\_info.hThread);
    }
    
    WaitForSingleObject(data->process\_info.hProcess, INFINITE);
    
    CloseHandle(data->process\_info.hProcess);
    
    data->process\_info.hProcess = 0;
    return (0);
    

    }

    int SystemCapture(
    TCHAR* CmdLine, //Command Line
    TCHAR* CmdRunDir) //set to '.' for current directory
    {
    SECURITY_ATTRIBUTES security_attributes;

    data.CmdLine = CmdLine;
    data.CmdRunDir = CmdRunDir;
    security\_attributes.nLength = sizeof(SECURITY\_ATTRIBUTES);
    security\_attributes.bInheritHandle = TRUE;
    security\_attributes.lpSecurityDescriptor = nullptr;
    data.startup\_info.cb = sizeof(STARTUPINFO);
    data.startup\_info.hStdInput = 0;
    data.startu
    
    L Offline
    L Offline
    Lukasz Gesieniec
    wrote on last edited by
    #10

    This code is working. Now I will try to analyze outputs and build GUI. I am not sure if can I use the code in C# WPF application. If not I will try to build GUI using Win API starting from your examples. Thank you.

    L 1 Reply Last reply
    0
    • L Lukasz Gesieniec

      This code is working. Now I will try to analyze outputs and build GUI. I am not sure if can I use the code in C# WPF application. If not I will try to build GUI using Win API starting from your examples. Thank you.

      L Offline
      L Offline
      leon de boer
      wrote on last edited by
      #11

      It's a simple background worker thread it will work without issue in a C# WPF application. How to: Use a Background Worker[^] Inside the worker thread you want a standard command execute

      static void runCommand() {
      //* Create your Process
      Process process = new Process();
      process.StartInfo.FileName = "cmd.exe";
      process.StartInfo.Arguments = "/c yourfile.exe";
      process.StartInfo.UseShellExecute = false;
      process.StartInfo.RedirectStandardOutput = true;
      process.StartInfo.RedirectStandardError = true;
      //* Set your output and error (asynchronous) handlers
      process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
      process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
      //* Start process and handlers
      process.Start();
      process.BeginOutputReadLine();
      process.BeginErrorReadLine();
      process.WaitForExit();
      }
      static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) {
      //* Do your stuff with the output (write to console/log/StringBuilder)
      Console.WriteLine(outLine.Data);
      }

      In vino veritas

      L 1 Reply Last reply
      0
      • L leon de boer

        It's a simple background worker thread it will work without issue in a C# WPF application. How to: Use a Background Worker[^] Inside the worker thread you want a standard command execute

        static void runCommand() {
        //* Create your Process
        Process process = new Process();
        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.Arguments = "/c yourfile.exe";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        //* Set your output and error (asynchronous) handlers
        process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
        process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
        //* Start process and handlers
        process.Start();
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();
        process.WaitForExit();
        }
        static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) {
        //* Do your stuff with the output (write to console/log/StringBuilder)
        Console.WriteLine(outLine.Data);
        }

        In vino veritas

        L Offline
        L Offline
        Lukasz Gesieniec
        wrote on last edited by
        #12

        I do simple test and problem is the same as before. Only when console app quits OutputHandler is executed and then I can read every line by line that app prints during running. Furthermore, it seems that StandardInput is not redirected because click on the button does not quit the app. App quits when 'e' key is pressed in the console window.

        public partial class MainWindow : Window
        {
            Process process = new Process();
        
            public MainWindow()
            {
                InitializeComponent();
                runCommand();
            }
        
            private void button\_Click(object sender, RoutedEventArgs e)
            {
                textBox.Text += "test\\r\\n";
                process.StandardInput.Write('e');
            }
        
            void runCommand()
            {
                //\* Create your Process
                
                process.StartInfo.FileName = "c:\\\\ConsoleApp.exe";
                process.StartInfo.Arguments = ".";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardInput = true;
                //\* Set your output and error (asynchronous) handlers
                process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
                process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
                
                //\* Start process and handlers
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                //            process.WaitForExit();
            }
            void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
            {
                //\* Do your stuff with the output (write to console/log/StringBuilder)
                Console.WriteLine(outLine);
            }
        }
        
        L 2 Replies Last reply
        0
        • L Lukasz Gesieniec

          I do simple test and problem is the same as before. Only when console app quits OutputHandler is executed and then I can read every line by line that app prints during running. Furthermore, it seems that StandardInput is not redirected because click on the button does not quit the app. App quits when 'e' key is pressed in the console window.

          public partial class MainWindow : Window
          {
              Process process = new Process();
          
              public MainWindow()
              {
                  InitializeComponent();
                  runCommand();
              }
          
              private void button\_Click(object sender, RoutedEventArgs e)
              {
                  textBox.Text += "test\\r\\n";
                  process.StandardInput.Write('e');
              }
          
              void runCommand()
              {
                  //\* Create your Process
                  
                  process.StartInfo.FileName = "c:\\\\ConsoleApp.exe";
                  process.StartInfo.Arguments = ".";
                  process.StartInfo.UseShellExecute = false;
                  process.StartInfo.RedirectStandardOutput = true;
                  process.StartInfo.RedirectStandardError = true;
                  process.StartInfo.RedirectStandardInput = true;
                  //\* Set your output and error (asynchronous) handlers
                  process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
                  process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
                  
                  //\* Start process and handlers
                  process.Start();
                  process.BeginOutputReadLine();
                  process.BeginErrorReadLine();
                  //            process.WaitForExit();
              }
              void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
              {
                  //\* Do your stuff with the output (write to console/log/StringBuilder)
                  Console.WriteLine(outLine);
              }
          }
          
          L Offline
          L Offline
          leon de boer
          wrote on last edited by
          #13

          Yes because you didn't put it in a worker thread :-) You need runCommand() to be in a worker thread .. it has to execute in the background so you can keep the WPF framework running in the foreground. Look back at the windows code I had to do the same thing the CreateProcess(...) is inside a function which is spawned into it's own thread via CreateThread. Unfortunately I don't use C# enough to know the code for making a worker thread off the top of my head. I actually don't have the WPF framework installed on my VisualStudio at the moment to work it out. Basically however we can describe it 1.) everything in runCommand() needs to go inside the worker thread start function .. when the thread starts it runs the app 2.) When the app finishes or your WPF app finishes you need to close the worker thread (LOOK at WM_DESTROY on the windows code) So basically this worker thread will be chugging along in the background running the app but your program comes back to you to continue on to run the WPF framework. So you job is to work out how to make a WPF worker thread and incorporate the code :-)

          In vino veritas

          1 Reply Last reply
          0
          • L Lukasz Gesieniec

            I do simple test and problem is the same as before. Only when console app quits OutputHandler is executed and then I can read every line by line that app prints during running. Furthermore, it seems that StandardInput is not redirected because click on the button does not quit the app. App quits when 'e' key is pressed in the console window.

            public partial class MainWindow : Window
            {
                Process process = new Process();
            
                public MainWindow()
                {
                    InitializeComponent();
                    runCommand();
                }
            
                private void button\_Click(object sender, RoutedEventArgs e)
                {
                    textBox.Text += "test\\r\\n";
                    process.StandardInput.Write('e');
                }
            
                void runCommand()
                {
                    //\* Create your Process
                    
                    process.StartInfo.FileName = "c:\\\\ConsoleApp.exe";
                    process.StartInfo.Arguments = ".";
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.RedirectStandardInput = true;
                    //\* Set your output and error (asynchronous) handlers
                    process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
                    process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
                    
                    //\* Start process and handlers
                    process.Start();
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    //            process.WaitForExit();
                }
                void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
                {
                    //\* Do your stuff with the output (write to console/log/StringBuilder)
                    Console.WriteLine(outLine);
                }
            }
            
            L Offline
            L Offline
            leon de boer
            wrote on last edited by
            #14

            If you want a total guess looking at the MSDN reference and your code but ignoring the exit problem ;-)

            using System.Threading;
            new Thread(() =>
            {
            Thread.CurrentThread.IsBackground = true;
            runCommand();
            }).Start();

            L 1 Reply Last reply
            0
            • L leon de boer

              If you want a total guess looking at the MSDN reference and your code but ignoring the exit problem ;-)

              using System.Threading;
              new Thread(() =>
              {
              Thread.CurrentThread.IsBackground = true;
              runCommand();
              }).Start();

              L Offline
              L Offline
              Lukasz Gesieniec
              wrote on last edited by
              #15

              Running runCommand() from new Thread didn't help. I can read all outputs after console app quits. It is harder to build GUI using WinAPI than using WPF but WinAPI code works.

              L 1 Reply Last reply
              0
              • L Lukasz Gesieniec

                Running runCommand() from new Thread didn't help. I can read all outputs after console app quits. It is harder to build GUI using WinAPI than using WPF but WinAPI code works.

                L Offline
                L Offline
                leon de boer
                wrote on last edited by
                #16

                Okay the problem is console.writeline is blocking C# test.net » Using Process.Start to capture console output[^] .net - Does Console.WriteLine block? - Stack Overflow[^] You can use one of the methods or Console.Out.WriteLineAsync("..."); if available. For us old timers it's actually faster to build a GUI with the API than with the WPF framework :-)

                In vino veritas

                L 1 Reply Last reply
                0
                • L leon de boer

                  Okay the problem is console.writeline is blocking C# test.net » Using Process.Start to capture console output[^] .net - Does Console.WriteLine block? - Stack Overflow[^] You can use one of the methods or Console.Out.WriteLineAsync("..."); if available. For us old timers it's actually faster to build a GUI with the API than with the WPF framework :-)

                  In vino veritas

                  L Offline
                  L Offline
                  Lukasz Gesieniec
                  wrote on last edited by
                  #17

                  OK, I know what you mean :) For me, it is easier to use WPF because I am embedded system engineer. I am from embedded world and I do not know Windows internals. That is why I am asking a lot of (stupid) questions. After reading several articles I supposed that redirect output and develop GUI app should be easier :) Now I know that my strange console app does not use standard printf function :((

                  L 1 Reply Last reply
                  0
                  • L Lukasz Gesieniec

                    OK, I know what you mean :) For me, it is easier to use WPF because I am embedded system engineer. I am from embedded world and I do not know Windows internals. That is why I am asking a lot of (stupid) questions. After reading several articles I supposed that redirect output and develop GUI app should be easier :) Now I know that my strange console app does not use standard printf function :((

                    L Offline
                    L Offline
                    leon de boer
                    wrote on last edited by
                    #18

                    The obvious question is can you not simply replace the program communicating with a proper windows code or is it a private format they won't disclose. Just saying it would be faster, cleaner and less code than what you are doing now :-)

                    In vino veritas

                    L 1 Reply Last reply
                    0
                    • L leon de boer

                      The obvious question is can you not simply replace the program communicating with a proper windows code or is it a private format they won't disclose. Just saying it would be faster, cleaner and less code than what you are doing now :-)

                      In vino veritas

                      L Offline
                      L Offline
                      Lukasz Gesieniec
                      wrote on last edited by
                      #19

                      Yes, it is a private closed format. Another way to communicate with the console app is passing command line arguments:

                      MyApp.exe -Iinput.txt -Ooutput.txt

                      where in the input.txt file in each line is a key command (e - exits the program, other keys do some actions): l f m c o e in the output.txt file, the program saves its output. Even something like this works: MyApp.exe -OCON - prints output to console twice. But problem is the same. If I monitor the output file, the content appears after app quits (e command in input file)

                      P 1 Reply Last reply
                      0
                      • L Lukasz Gesieniec

                        Yes, it is a private closed format. Another way to communicate with the console app is passing command line arguments:

                        MyApp.exe -Iinput.txt -Ooutput.txt

                        where in the input.txt file in each line is a key command (e - exits the program, other keys do some actions): l f m c o e in the output.txt file, the program saves its output. Even something like this works: MyApp.exe -OCON - prints output to console twice. But problem is the same. If I monitor the output file, the content appears after app quits (e command in input file)

                        P Offline
                        P Offline
                        Peter_in_2780
                        wrote on last edited by
                        #20

                        This smells to me of buffering. I'm guessing your app doesn't call flush() or equivalent on its output file, so the output is buffered until the explicit or implicit close() call at termination. If you can make your app output lots of data, you will probably see it appear in chunks, which will be whatever buffer size is used. The reason it works on the console is that console drivers do not buffer. I have no idea if you can suppress buffering in your redirection, but if you could, my 2c says that would solve your problem. Good luck! Peter

                        Software rusts. Simon Stephenson, ca 1994. So does this signature. me, 2012

                        L 1 Reply Last reply
                        0
                        • P Peter_in_2780

                          This smells to me of buffering. I'm guessing your app doesn't call flush() or equivalent on its output file, so the output is buffered until the explicit or implicit close() call at termination. If you can make your app output lots of data, you will probably see it appear in chunks, which will be whatever buffer size is used. The reason it works on the console is that console drivers do not buffer. I have no idea if you can suppress buffering in your redirection, but if you could, my 2c says that would solve your problem. Good luck! Peter

                          Software rusts. Simon Stephenson, ca 1994. So does this signature. me, 2012

                          L Offline
                          L Offline
                          leon de boer
                          wrote on last edited by
                          #21

                          Yes standard console output is always buffered. You can actually easily remove it

                          setvbuf(stdout, NULL, _IONBF, 0);
                          setvbuf(stderr, NULL, _IONBF, 0);

                          The problem is it will slow the console program down like a dog as each character invokes a full call. I sometimes do it when I have a embedded target with UART debugger like on the Raspberry Pi.

                          In vino veritas

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups