<!-- Download Links -->
<!-- Add the rest of your HTML here -->
Console windows and application output
During a "simple" project I discovered the tedious task of capturing the output of a console window into a control of the application. The additional difficulty was to hide the console window, thus
hiding the application.
As it was to be expected, things were not as easy as redirecting output into a file and reading that file back in.
So I started creating a wrapper class for this task and it proved harder than
it seemed at first. The provided sample in the MSDN did not mention the most important things and leaves more questions then it solves.
Searching around on various code sites shed some more light on the topic. Finally I could assemble a working solution. (Although there are some minor wishes left)
The CSpawn Class
This class has a pretty simple interface. A constructor, an execute function, an output
function and finally a test to see if it is still active. The execute function and
the output function are available in various flavours.
For the feedback you must derive a class from
CSpawnConsumer and overload the
Usually it looks like this:
class CSpawnConsumer1 : public CSpawnConsumer
explicit CSpawnConsumer1(CMyEdit* pEdit)
void Consume(TCHAR* p, DWORD dw)
This class is called from the thread reading the output of the console window.
You can use the
CSpawn class in two ways:
- Using the constructor method
CSpawn::CSpawn(CString& exe, CSpawnConsumer* sc)
- Or creating a
CSpawn variable and calling
Execute(CString& exe, CSpawnConsumer* sc)
The default implementation will spawn the executable by resolving the ComSpec environment
variable (normally CMD.EXE or COMMAND.EXE) and passing parameters to the given application.
You can provide user input to a running application by calling
The included sample project shows a simple edit control where any text entered is passed to the standard command interpreter and returns the results into the same edit control.
It shows how to interface with the
CSpawn class in the most common way.
CSpawn was tested under Windows 2000 and Windows XP in Unicode and MBCS (both included in
demo project) using Visual C++ 6.0 SP5 and MFC 6.
Its not tested with .NET and MFC 7.
19 Jun 2002 - Initial Revision