为WIN32窗口应用程序附加控制台窗口,方便输入输出调试信息

 转自:http://www.codeguru.com/Cpp/W-D/console/redirection/article.php/c3961/

 

 

// ConsoleWinApp.cpp : implementation file
//

#include "stdafx.h"

#ifdef _CONSOLEWIN
//Set subsystem to console
#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
int _tmain( DWORD, TCHAR**, TCHAR** )
{
#define SPACECHAR   _T(' ')
#define DQUOTECHAR  _T('/"')

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

   // Get command lin
	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);

	return _tWinMain(::GetModuleHandle(NULL), NULL, lpszCommandLine,
		(StartupInfo.dwFlags & STARTF_USESHOWWINDOW) ?
		StartupInfo.wShowWindow : SW_SHOWDEFAULT);
}

#endif // _CONSOLEWIN

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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值