Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

c++ - Windows GUI + Console Output, Linux-style

I have a GUI application, which I am developing cross-platform for Linux and Windows. On Linux, everything works smoothly. However, I've run into a hitch on Windows. I would like to be able to log certain messages to the console with a GUI app on Windows, Linux-style.

What I mean by Linux-style is, if the program is opened from a console, the output will go to the console, but if the program is opened, for example, through the start menu, the user will never see console output. Apparently, this is harder than it sounds on Windows.

Currently, I use the following trickery in main():

#if _WINDOWS /* Fix console output on Windows */
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
    freopen("CONOUT$","wb",stdout);
    freopen("CONOUT$","wb",stderr);
}
#endif

This allows me to create output before a window is actually opened by the program, such as responding to "--help" from the command line. However, once a window is actually initialized and opened by my program, the console is returned. I need a solution that will allow me continued access to the console throughout the life of my program, without opening a new console if none was originally used.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We use ::AllocConsole() instead of ::AttachConsole and it remains open throughout the app. Try that?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...