我正在使用Visual Studio编写一个简单的基于对话框的程序。它应该执行其主要功能。然后我添加了从命令提示符运行应用程序的支持。从命令行提示符调用程序时,它仍然可以正常工作,但是不会显示写入stdout
或stderr
的任何消息。
我尝试了_tprintf()
,_ftprintf(stdout, etc)
的多种变体,依此类推。无论如何,我都没有在控制台上获得任何输出。
当命令行包含至少两个参数时,程序会绕过对话框并直接执行程序的主逻辑,该逻辑体现在Go(arg1, arg2)
函数中。如果命令行没有足够的参数,则使用对话框。
这是一个非常精简的例子。剩下的大部分内容都是由Visual Studio生成的,我刚刚添加了几行代码。这个例子实际上不会编译,因为有未解析的外部引用。
BOOL CCNCSplineApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
std::time_t* p_clock = &time_now;
CWinApp::InitInstance();
AfxEnableControlContainer();
// Create the shell manager, in case the dialog contains
// any shell tree view or shell list view controls.
CShellManager *pShellManager = new CShellManager;
// Standard initialization
SetRegistryKey(_T("MyCompany"));
LPCTSTR cmdline = ::GetCommandLineW();
int argc;
LPWSTR* argv = ::CommandLineToArgvW(cmdline, &argc);
if (2 < argc)
{
FILE*tgt = _tfopen(argv[2], _T("w"));
if (0 == tgt)
{
_tprintf(L"Unable to open output file \"%s\"\n", argv[2]);
exit(-1);
}
CString inputFileName = argv[1];
Go(inputFileName, tgt);
CString status = StatusText();
if (status.GetLength() > 0)
{
_tprintf(_T("%s\n"), (LPCTSTR)status);
}
return FALSE;
}
MyDialog dlg;
m_pMainWnd = &dlg;
dlg.DoModal();
// Delete the shell manager created above.
if (pShellManager != NULL)
{
delete pShellManager;
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application'time_doa message pump.
return FALSE;
}
我需要在此代码中更改以获取各种_tprintf()
调用以在控制台上显示文本?
答案 0 :(得分:3)
将此代码插入InitInstance()
中的某个位置,之后printf()
,std::cout
等应该有效:
if( AttachConsole( ATTACH_PARENT_PROCESS ) )
{
freopen( "CONIN$", "rb", stdin ); // reopen stdin handle as console window input
freopen( "CONOUT$", "wb", stdout ); // reopen stout handle as console window output
freopen( "CONOUT$", "wb", stderr ); // reopen stderr handle as console window output
}
您可能还想将_setmode(_fileno(stdout), _O_U16TEXT)
(stderr
的相同内容)致电enable Unicode output to the console。