Allocating a console inside an MFC program

>> Sunday, October 18, 2009


If you want to write the text out to the console while this is an MFC program. Here's the tip:

The thing to be remarked here is the function AllocConsole, it's called inside function InitInstance() of the App class.


// button.cpp
// compile with : cl /EHsc button.cpp /link /SUBSYSTEM:WINDOWS /RELEASE
#include "afxwin.h"
#include "iostream"
using namespace std;

#define IDB_BUTTON 100

// Declare the handles for the console
HANDLE consoleStdout, consoleStdin;

// Declare the application class
class CButtonApp : public CWinApp
{
public:
virtual BOOL InitInstance();
};

// Create an instance of the application class
CButtonApp ButtonApp;

// Declare the main window class
class CButtonWindow : public CFrameWnd
{
CButton *button;
public:
CButtonWindow();
~CButtonWindow();
afx_msg void HandleButton();

DECLARE_MESSAGE_MAP()
};

// The message handler function
void CButtonWindow::HandleButton()
{
DWORD n;

Beep(700,100);
// Two different ways to write to the console
WriteFile(consoleStdout, "hello\n", 6, &n, 0);
cout << "test string" << endl;}// The message mapBEGIN_MESSAGE_MAP(CButtonWindow, CFrameWnd) ON_COMMAND(IDB_BUTTON, HandleButton)END_MESSAGE_MAP()// The InitInstance function is called once// when the application first executesBOOL CButtonApp::InitInstance(){ // Create an auxiliary console for cout to use. // As soon as this function returns you // can write to it. AllocConsole(); // Get handles for standard in and out consoleStdin = GetStdHandle(STD_INPUT_HANDLE); consoleStdout = GetStdHandle(STD_OUTPUT_HANDLE); // they must be invalid if equal if (consoleStdin == consoleStdout) return FALSE; m_pMainWnd = new CButtonWindow(); m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();

return TRUE;
}

// The constructor for the window class
CButtonWindow::CButtonWindow()
{
CRect r;

// Create the window itself
Create(NULL,
"CButton Tests",
WS_OVERLAPPEDWINDOW,
CRect(0,0,200,200));

// Get the size of the client rectangle
GetClientRect(&r);
r.InflateRect(-20,-20);

// Create a button
button = new CButton();
button->Create("Push me",
WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,
r,
this,
IDB_BUTTON);
}

// The destructor for the window class
CButtonWindow::~CButtonWindow()
{
delete button;
CFrameWnd::~CFrameWnd();
}

0 comments: