How to display cmd prompt after printing output to cmd.exe?

馋奶兔 提交于 2020-05-27 13:21:09

问题


I have an winmain application that is executed from cmd.exe and prints output to it. I atach to the cmd.exe using AttachConsole(ATTACH_PARENT_PROCESS). After application is executed and output is printed to cmd.exe command line prompt is not displayed and it looks like application is stil running(while it is already closed). Before closing my application I release the console using FreeConsole().

#include <iostream>
#include <fstream>
#include <windows.h>

int wWinMain
(
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPWSTR lpCmdLine,
    int nCmdShow
) 
    {
    AttachConsole(ATTACH_PARENT_PROCESS);

    std::wofstream console_out("CONOUT$");
    std::wcout.rdbuf(console_out.rdbuf());

    std::wcout << L"\nSome Output" << std::endl;

    FreeConsole();

    return 0;
    }

Current result:

My goal:

How should I make prompt C:New folder> appear after myapp.exe has printed its output and is closed.


回答1:


In case the question has not been answered yet (after such a long time), it is required to simulate the actual pressing of the 'Enter' key in the console window by sending (or, preferably, posting) the corresponding WM_KEYDOWN message to the console window, i.e.

after std::wcout << L"\nSome Output" << std::endl;

and before calling FreeConsole(), insert the following:

HWND hWndCon_ = ::GetConsoleWindow();
 if( hWndCon_ ) {
    ::PostMessage( hWndCon_, WM_KEYDOWN, VK_RETURN, 0 );
 }

or simply

::PostMessage( ::GetConsoleWindow(), WM_KEYDOWN, VK_RETURN, 0 );



来源:https://stackoverflow.com/questions/38974182/how-to-display-cmd-prompt-after-printing-output-to-cmd-exe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!