[英]AttachConsole() does not take user-input as expected
我們有一個可以在 GUI 和控制台模式下運行的應用程序 - 所以我們將其設置為 SUBSYSTEM:WINDOWS。 現在,當從控制台調用它時,我們希望它通過“附加到父控制台”來“在控制台模式下運行”。 為此,我們使用 AttachConsole() 並將 stdin/stdout 流式傳輸到此控制台。 如下代碼所示:
if(AttachConsole (ATTACH_PARENT_PROCESS) == 0){
// Not launched from a console
}else{
// launched via a console
FILE * fpstdin = stdin, *fpstdout = stdout, *fpstderr = stderr;
freopen_s (&fpstdin, "CONIN$", "r", stdin);
freopen_s (&fpstdout, "CONOUT$", "w", stdout);
freopen_s (&fpstderr, "CONOUT$", "w", stderr);
}
構建的應用程序 (exe) 從 cmd 運行。 當我們這樣做時,我們觀察到幾個問題:
當從 cmd 啟動 exe 時,期望 exe 特定的用戶交互(即輸入/輸出)應在同一 cmd 終端中繼續,而不會在兩者之間重新出現 cmd 提示。 然而觀察是 cmd 提示重新出現在 exe 特定用戶交互之間。 下面提供的圖片供參考: AttachConsole() 的標准輸入問題
運行exe再次顯示cmd提示然后應用程序的output來了即
C:\Test>MySampleApp.exe
C:\Test>這是來自 MySampleApp.exe 的 output... 等等。
你能告訴我們我們做錯了什么嗎?
對我來說,這很有效(?)(我不太了解我在代碼中寫的內容,我是使用 Windows API、C 和 C++ 的初學者)。
#include <iostream>
#include <Windows.h>
#include <tchar.h>
int APIENTRY _tWinMain(
const HINSTANCE _In_ CurrInst,
const HINSTANCE _In_opt_ PrevInst,
const PTSTR _In_ CmdLine ,
const int _In_ CmdShow ) {;
if (AttachConsole(ATTACH_PARENT_PROCESS) == 0) {
// Not launched from a console
AllocConsole();
FILE * fpstdin = stdin,
* fpstdout = stdout,
* fpstderr = stderr;
_tfreopen_s(&fpstdin, _T("CONIN$"), _T("r"), stdin);
_tfreopen_s(&fpstdout, _T("CONOUT$"), _T("w"), stdout);
_tfreopen_s(&fpstderr, _T("CONOUT$"), _T("w"), stderr);
std::cout << "Attached!\n";
std::cin.get();
} else {
// Launched from a console
AllocConsole();
FILE * fpstdin = stdin ,
* fpstdout = stdout,
* fpstderr = stderr;
_tfreopen_s(&fpstdin , _T("CONIN$" ), _T("r"), stdin );
_tfreopen_s(&fpstdout, _T("CONOUT$"), _T("w"), stdout);
_tfreopen_s(&fpstderr, _T("CONOUT$"), _T("w"), stderr);
std::cout << "Not Attached!\n";
std::cin.get();
}
FreeConsole();
}
我認為封裝其中一些指令可能很有用,您可以在 Alloc/Free 控制台上使用 RAII?
編輯:是的,我看到了“重復代碼”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.