I've been busy coding a application that functions as a frontend: it has a GUI taking command line options with buttons and things like that and passing them to a command line .exe. It uses the console of the application to display the output of the command line app. This works fine, but when using Ctrl+C or trying to close the console window, the GUI closes too, which is not really what I want. However, letting the program output with it's own console is not possible because it batch-processes files and every file would pop up it's own console.
The program is written in C++ with MSVC 2012 and uses .NET. I tried Console::CancelKeyPress to at least get Ctrl+C behave as I want it to (stop the command-line app but not the GUI) but have some trouble with this.
My code
private: System::Void OnCancelKeyPressed(System::Object^ sender, System::ConsoleCancelEventArgs^ e) {
e->Cancel = true;
}
private: System::Void GetConsoleReady() {
COORD c;
FreeConsole();
AllocConsole();
c.X = 80; c.Y = 8000;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),c);
Console::Clear();
Console::TreatControlCAsInput = false;
Console::CancelKeyPress +=
gcnew ConsoleCancelEventHandler(this, &Form1::OnCancelKeyPressed);
}
This gets called every time a user tries to run a batch of files to process. After running the batch, the console is released with FreeConsole(). The first time it works nice and using Ctrl+C kills the command line app but the processing in the GUI continues, running other commands and finally using FreeConsole(). However, when trying to do this a second time, it kills the GUI as well. I tried to add this before adding the new event to remove the previous event
Console::CancelKeyPress -=
gcnew ConsoleCancelEventHandler(this, &Form1::OnCancelKeyPressed);
But somehow that raises an error on adding the handler, but only the second time: An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll, Additional information: De parameter is onjuist.
That last part is Dutch for 'wrong argument', and the debugger says it chokes on readding the ConsoleCancelEventHandler.
If I try to add the event handler only once by adding it when loading of the form it does nothing.
What is going on here?