【问题标题】:Console using APIENTRY closes immediately使用 APIENTRY 的控制台立即关闭
【发布时间】:2021-06-30 20:08:39
【问题描述】:

Visual Studio 不会显示任何错误,但在使用调试或不使用控制台运行时会立即关闭。我使用了一个while循环来防止它关闭但不显示printf字符串。 这是我的代码:

#include <Windows.h>

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR    lpCmdLine,
    _In_ int       nCmdShow)
{
    AllocConsole(); 
    HWND windowHandle = FindWindowA("ConsoleWindowClass", NULL);
    ShowWindow(windowHandle, 10);

    printf("Blehh");

    return 0;
}

【问题讨论】:

  • 但是你真的在这里等什么?你从 wWinMainExitProcess 中退出调用
  • 附带说明,您可以使用GetConsoleWindow()获取与调用进程关联的控制台的HWND,您不需要使用FindWindow(),如果可能会发现错误的窗口一次有多个控制台处于活动状态。
  • 只需要控制台保持打开并显示 printf 字符串
  • @YashMalviya 问题是进程终止,销毁它创建的控制台,一旦wWinMain() 退出,所以你需要阻止它退出,就像 paulsm4 的答案显示的那样

标签: c winapi


【解决方案1】:

您需要将标准输入和输出重定向到创建的控制台,并在输出后刷新缓冲区。

代码如下:

#include <Windows.h>
#include <stdio.h>

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR    lpCmdLine,
    _In_ int       nCmdShow)
{
    AllocConsole();
    HWND windowHandle = FindWindowA("ConsoleWindowClass", NULL);
    ShowWindow(windowHandle, SW_NORMAL);
    FILE* fDummy;
    freopen_s(&fDummy, "CONIN$", "r", stdin);
    freopen_s(&fDummy, "CONOUT$", "w", stderr);
    freopen_s(&fDummy, "CONOUT$", "w", stdout);
    printf("Blehh");
    fflush(fDummy);
    system("pause");
    return 0;
}

它对我有用。

【讨论】:

    【解决方案2】:

    尝试在“返回 0”之前添加“暂停”;例如getchar();system("pause");

    #include <windows.h>
    #include <stdlib.h>
    
    int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
        _In_opt_ HINSTANCE hPrevInstance,
        _In_ LPWSTR    lpCmdLine,
        _In_ int       nCmdShow)
    {
        AllocConsole(); 
        HWND windowHandle = FindWindowA("ConsoleWindowClass", NULL);
        ShowWindow(windowHandle, 10);
    
        printf("Blehh");
        system("pause");
    
        return 0;
    }
    

    【讨论】:

    • 这确实有效,但不显示 printf 字符串。就像我说的那样,我之前使用了 while 循环来防止它
    • @YashMalviya printf() 通常是行缓冲的。试试printf("Blehh\n");
    • @YashMalviya:1)你已经修复了“消失的窗口”;)很好。 2) DaV 正确:C 库函数使用buffered I/O。一种解决方案是将“\n”(DOS 回车/换行)添加到您的 printf 字符串中。另一种是致电fflush()。如果您觉得此回复有帮助,请“点赞”和/或“接受”。
    猜你喜欢
    • 2012-08-06
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 2018-07-30
    • 2018-12-06
    • 2020-07-03
    相关资源
    最近更新 更多