可选择使用C ++写入控制台的Windows应用程序? [英] Windows application that optionally writes to a console in C++?

查看:169
本文介绍了可选择使用C ++写入控制台的Windows应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个具有以下行为的Windows应用程序:

1.如果从现有的命令行窗口(cmd.exe)启动,那么它将其stdout写入该控制台。

2.如果通过双击其图标启动它,它不会打开一个新的控制台,并且不会在任何地方写入它的stdout。

I'd like to have a windows application with the following behaviour:
1. if it is started from an existing command line window (cmd.exe) then it writes its stdout to that console.
2. If it is started by double clicking its icon, it doesn't open a new console and doesn't write its stdout anywhere.

为了实现只有1,我可以设置 / SUBSYSTEM 链接器参数 CONSOLE 但然后如果我双击应用程序图标,将打开一个新的控制台窗口。

要实现2,我为 WINDOWS 设置相同的参数,但是如果我从控制台,它的stdout不指向控制台。

我想让同一个可执行文件具有这两种行为。

To achieve just 1, I can set the /SUBSYSTEM linker argument to CONSOLE but then if I double click the app icon, a new console window is opened.
To achieve 2, I set the same argument to WINDOWS, but then if I start the app from the console, its stdout is not directed to the console.
I want the same executable to have both behaviors.

到目前为止,我发现是我可以创建 / SUBSYSTEM:WINDOWS 可执行文件并执行此操作:

So far what I found is that I can create a /SUBSYSTEM:WINDOWS executable and do this:

DWORD ret = AttachConsole(ATTACH_PARENT_PROCESS)
if (ret != 0) {  // succeeds only if the parent is cmd.exe
     HANDLE outh = GetStdHandle(STD_OUTPUT_HANDLE);
     WriteFile(outh, "Hello", 5, NULL, NULL);
}

这会写入 Hello 到控制台,如果进程从一个开始,并且什么都不做其他。

现在只是有一个问题,CRT让 outh 作为HANDLE for stdout。我如何做到这一点?

This writes Hello to the console if the process was started from one and does nothing otherwise.
Now there is just the problem of getting the CRT to take outh as the HANDLE for stdout. How can I do that?

此选项的另一个问题是cmd.exe不阻止启动的进程。一旦新进程启动,cmd.exe只是回到提示符,并且在提示符下出现 Hello 字符串。如果用户在控制台上按Enter键,则会出现另一个提示。关于如何防止这种情况的任何想法?

Another problem with this option is that the cmd.exe is not blocking on the started process. Once the new process is started, cmd.exe just goes back to the prompt and the Hello string appears right there at the prompt. If the user presses Enter on the console, another prompt appears. Any idea on how to prevent that?

推荐答案

找到答案: http://dslweb.nwnexus.com/~ast/dload/guicon.htm

DWORD ret = AttachConsole(-1);
if (ret != 0) {
   HANDLE lStdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
   int hConHandle = _open_osfhandle((intptr_t)lStdHandle, 0);
   FILE* fp = _fdopen( hConHandle, "w" );
   *stdout = *fp;
}

至于cmd.exe等待,似乎不可能:
http://blogs.msdn.com /b/oldnewthing/archive/2009/01/01/9259142.aspx

And as for making cmd.exe wait, that doesn't seem possible: http://blogs.msdn.com/b/oldnewthing/archive/2009/01/01/9259142.aspx

这篇关于可选择使用C ++写入控制台的Windows应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆