Windows Applications that Have Access To Console Features

.


Click here for larger image

Overview

I always wanted to use cout, cin, cerr, printf, etc. in windows application if  I started it from command line. There was an article ( http://www.codeguru.com/console/dualmode.html, contributed Richard Eperjesi) about how the MSDEV can work in console mode (MSDEV /?) and in windows mode (MSDEV). That's a very great idea, and here is another tricky way.

Usage

Crete your MFC windows project and add the ConsoleWindowsApp.cpp or this source code to your project, and 
  • Do Define _CONSOLEWIN in your project settings, if you want your project to work like a console and windows application. The standard output, and input will be redirected to the parent console. You can use cout, cerr, cin, printf, etc.
  • Do not define _CONSOLEWIN in your project settings, and you will get a windows application. (Default)

Source code

#ifdef _CONSOLEWIN

//Set subsystem to console, just overwrites the default windows subsystem
#pragma comment ( linker, "/subsystem:console" )

BOOL WINAPI ConsoleWinHandlerRoutine( DWORD dwCtrlType )
{
    // Signal type
    switch( dwCtrlType )
    {
    case CTRL_C_EVENT:
    case CTRL_BREAK_EVENT:
    case CTRL_CLOSE_EVENT:
    case CTRL_LOGOFF_EVENT:
    case CTRL_SHUTDOWN_EVENT:
    // You can stop here gracefully:
    //
    // AfxGetMainWnd()->SendMessage( WM_CLOSE, 0, 0 );
    // WaitForSingleObject( AfxGetThread(), INFINITE );
    //
    ExitProcess(0);
    break;
}

return TRUE;
}

// Console main function, this code is from WinMainCRTStartup()
int _tmain( DWORD, TCHAR**, TCHAR** )
{
#define SPACECHAR _T(' ')
#define DQUOTECHAR _T('\"')

    // Set the new handler
    SetConsoleCtrlHandler( ConsoleWinHandlerRoutine, TRUE );


    // Get command line
    LPTSTR lpszCommandLine = ::GetCommandLine();

    if(lpszCommandLine == NULL)
        return -1;

    // Skip past program name (first token in command line).
    // Check for and handle quoted program name.
    if(*lpszCommandLine == DQUOTECHAR)
    {
        // Scan, and skip over, subsequent characters until
        // another double-quote or a null is encountered.
        do
        {
            lpszCommandLine = ::CharNext(lpszCommandLine);
        } while((*lpszCommandLine != DQUOTECHAR) && (*lpszCommandLine != _T('\0')));

        // If we stopped on a double-quote (usual case), skip over it.
        if(*lpszCommandLine == DQUOTECHAR)
            lpszCommandLine = ::CharNext(lpszCommandLine);
    }
    else
    {
        while(*lpszCommandLine > SPACECHAR)
            lpszCommandLine = ::CharNext(lpszCommandLine);
    }

    // Skip past any white space preceeding the second token.
    while(*lpszCommandLine && (*lpszCommandLine <= SPACECHAR))
        lpszCommandLine = ::CharNext(lpszCommandLine);

    STARTUPINFO StartupInfo;
    StartupInfo.dwFlags = 0;

    ::GetStartupInfo(&StartupInfo);

    // Your original windows application will be started
    return _tWinMain(::GetModuleHandle(NULL), NULL, lpszCommandLine,
                (StartupInfo.dwFlags & STARTF_USESHOWWINDOW) ?
          StartupInfo.wShowWindow : SW_SHOWDEFAULT);
}

Downloads

Download source code - 2 Kb


Comments

  • Re-entering the Windows part

    Posted by dms489 on 03/31/2006 02:54pm

    I am trying (and perhaps I shouldn't) to use this technique to allow a console application to open a window to draw stuff, wait for it to close, then do some more computing and open another window. This second instantiation of MFC dies a quick, horrible death, and I was hoping someone knew how to fix that.

    Reply
  • How to create more than one Console Window

    Posted by Legacy on 07/25/2003 12:00am

    Originally posted by: H. Descho

    Does anyone know, how to create/show more than one Console application window??

    Reply
  • nucleus with VC++

    Posted by Legacy on 06/23/2003 12:00am

    Originally posted by: Prashanth sylvester

    if we use nuclues with VC++ is it possible to desin a GUI for the application ..!

    Reply
  • using cout AND cin

    Posted by Legacy on 02/22/2003 12:00am

    Originally posted by: Mr. Bungle

    This is very useful, however:

    is it possible to redirect cout in a graphical windows program (bc++b6) to a form's text control (e.g. memo control) and be able to use cin to retrieve use input in the control somehow?

    That would really be useful!

    MRB

    Reply
  • couldn't open STDAFX.H

    Posted by Legacy on 12/14/2002 12:00am

    Originally posted by: sorokano

    I got this error while compiling:
    >>fatal error C1083: Cannot open include file: 'StdAfx.h': No such file or directory

    where do i get stdafx.h?

    Reply
  • How to make hybrid GUI/console application truly seamless

    Posted by Legacy on 10/21/2002 12:00am

    Originally posted by: Akif

    This example is doing a useful thing however I should
    say it is not very desirable, since it requires re-compilation between pure GUI and console mode of the same application. Suppose I have a dialog based GUI application, I want to turn it it to a hybrid console application. What I mean by hybrid is: when user starts it from a command line, no GUI or GUI related stuff will be generated (this is my part and I can guarantee that) but I want to see cout, printf etc regular console outputs to be enabled..
    So the whole application should be seamless, between GUI and console mode. The example here always first creates a parent console, it is disturbing view when you only want GUI, and you don't want to re-compile.

    Reply
  • can you help me

    Posted by Legacy on 07/26/2002 12:00am

    Originally posted by: jianhua qu

    I didn't know how to use this ,and I hope you can send me a demo.
    thanks!

    Reply
  • Very Useful Program, but I can't stop it

    Posted by Legacy on 05/06/2002 12:00am

    Originally posted by: nomadeous

    This program is very useful for me,
    Thanks Zoltan.

    But I have a problem :
    I added _CONSOLEWIN to my project's settings like you told.
    But when I launch my prog, it works good, the cout messages appear in the console. But when I leave my prog by a PostQuitMessage(0), the console stays on.

    Please could you help me ?

    Reply
  • Eeeeeexcellent, Smithers!

    Posted by Legacy on 02/11/2002 12:00am

    Originally posted by: Migraine

    Well done. Simple and functional.

    Reply
  • Does not work

    Posted by Legacy on 02/07/2002 12:00am

    Originally posted by: Feroz Zahid

    The piece of code that you have provided to us doesn't work.
    Please try to make it less error prone.
    thanks

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • CentreCorp is a fully integrated and diversified property management and real estate service company, specializing in the "shopping center" segment, and is one of the premier retail service providers in North America. Company executives travel a great deal, carrying a number of traveling laptops with critical current business data, and no easy way to back up to the network outside the office. Read this case study to learn how CentreCorp implemented a suite of business continuity services that included …

Most Popular Programming Stories

More for Developers

RSS Feeds