Output to the parent console in Windows application
So I looked into boost.program_options today to parse command line arguments for my Windows Forms application. Which basically works great. Except for the little part to output the –help output to the console. Now, obviously when you start your application through Explorer you won’t have a console. And that is fine. I was only interested in the case when you start the application through a console window. Additionally it would also have to work with Unicode of course :P
So after looking around the web for a while I finally managed to put it all together. So here it is:
BOOL consoleAttached = AttachConsole( ATTACH_PARENT_PROCESS );
boost::program_options::options_description desc( "Allowed options" );
desc.add_options()
( "help", "Show this message" )
( "width", "Backbuffer width" )
( "height", "Backbuffer height" )
;
wstring commandLine = GetCommandLine();
int argc = 0;
LPWSTR* argv = 0;
argv = CommandLineToArgvW( commandLine.c_str(), &argc );
boost::program_options::variables_map vm;
boost::program_options::store( boost::program_options::parse_command_line( argc, argv, desc ), vm );
boost::program_options::notify( vm );
LocalFree( argv );
if( vm.count( "help" ) ) {
if( consoleAttached ) {
HANDLE hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if( INVALID_HANDLE_VALUE == hStdOut ) {
return 1;
}
DWORD dwCharsWritten;
std::stringstream desc_strings;
desc_strings << desc;
std::string desc_string = desc_strings.str();
WriteConsoleA( hStdOut, desc_string.c_str(), desc_string.length(), &dwCharsWritten, NULL );
FreeConsole();
}
return 1;
}
Sadly after the application finishes the prompt doesn’t instantly return. Maybe I’ll look into that some day…
