I have a winapi program that I wish to not open any windows if executed with command line arguments. I can attach to the parent console perfectly and WriteConsoleA()
works, but when I try to redirect C I/O, std::cout
, and std::cin
to the console (following the methodology of several StackOverflow posts about this subject), these will not write to the attached console as expected.
main.c -
#include <windows.h>
#include <stdio.h>
#include "cmd_line.h"
#include "dialog.h"
#include "resource.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
if(__argc > 1)
{
RedirectIOToConsole(); // Attaches and redirects
// Temporary tests
HANDLE consoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
char a[] = "hi";
WriteConsoleA(consoleOut, &a, 2, NULL, NULL); // Prints
printf("hi\n"); // Does not print
// External C++ function which performs my command line option via lots of std::cout and cin
CmdLine(__argc, __argv); // Does not print
}
else
// External C++ function to handle my winapi dialog
return DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAIN), NULL, DlgProc);
}
part of cmd_line.cpp which implements RedirectIOToConsole()
-
void RedirectIOToConsole()
{
int hConHandle;
long lStdHandle;
FILE *fp;
AttachConsole(ATTACH_PARENT_PROCESS);
// STDOUT to the console
lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stdout = *fp;
setvbuf( stdout, NULL, _IONBF, 0 );
// STDIN to the console
lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );
// STDERR to the console
lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stderr = *fp;
setvbuf( stderr, NULL, _IONBF, 0 );
// C++ streams to console
std::ios_base::sync_with_stdio();
}
Could someone please help me with a proper, working way to redirect stdio
and iostream
to this console? Thank you!