I have a problem with redirect console app output and input. The problem is that any example I found does not work for me. I want to develop WPF GUI for a console app. This is the example code to redirect output:
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:\\myapp.exe"; // Specify exe name.
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
So I did some reverse engineering on the console app and I found that this app is compiled using Microsoft Visual C 6.0. The app uses WriteFile to output to the console and first argument passed to the function equals 7.
I wrote the example code:
#include "stdafx.h"
#include <windows.h>
int main()
{
AllocConsole();
HANDLE hStdout;
HANDLE hStdout2 = (HANDLE)0x00000007;
char s[] = "Hello world !\r\n";
char s2[] = "Hello world !CONOUT\r\n";
char s3[] = "test\r\n";
DWORD dwBytesWritten;
HANDLE hScreenBuffer = CreateFileA("CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
hStdout = GetStdHandle(STD_OUTPUT_HANDLE); // hStdout equals 7 after this call
WriteFile(hStdout2, s3, (DWORD)strlen(s3), &dwBytesWritten, NULL); //prints always to console
WriteFile((HANDLE)0x00000007, s3, (DWORD)strlen(s3), &dwBytesWritten, NULL); //prints always to console
WriteFile(hStdout, s, (DWORD)strlen(s), &dwBytesWritten, NULL); //can be redirected; example TestCON.exe > test.txt
WriteFile(hScreenBuffer, s2, (DWORD)strlen(s2), &dwBytesWritten, NULL);//prints always to console
FreeConsole();
return 0;
}
I do not understand why this:
WriteFile(hStdout, s, (DWORD)strlen(s), &dwBytesWritten, NULL); (hStdout equals 7 checked by debuger)
is redirected using my above example code or TestCON.exe > test.txt
but this WriteFile((HANDLE)0x00000007, s3, (DWORD)strlen(s3), &dwBytesWritten, NULL);
is printed always on the console.
Any suggestions how can I redirect any output to my GUI app?
User contributions licensed under CC BY-SA 3.0