如何做一个"尊重"以前控制台内容的C#Windows控制台应用程序?

rob*_*prs 7 .net c# windows console

像Vim一样:当它启动时它会带你到另一个"缓冲区".当vim关闭时,用户会看到命令提示符的先前内容.

有人知道如何使用C#做到这一点吗?

谢谢

编辑:用户将不再看到应用程序的输出.希望能更好地解释它.

Jus*_*tin 5

我通过查看Vim源代码来解决这个问题,在mch_init函数的os_win32.c中可以找到相关的位,我在这里复制并粘贴了相关的位

    /* Obtain handles for the standard Console I/O devices */
    if (read_cmd_fd == 0)
    g_hConIn =  GetStdHandle(STD_INPUT_HANDLE);
    else
    create_conin();
    g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);

#ifdef FEAT_RESTORE_ORIG_SCREEN
    /* Save the initial console buffer for later restoration */
    SaveConsoleBuffer(&g_cbOrig);
    g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
#else
    /* Get current text attributes */
    GetConsoleScreenBufferInfo(g_hConOut, &csbi);
    g_attrCurrent = g_attrDefault = csbi.wAttributes;
#endif
    if (cterm_normal_fg_color == 0)
    cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
    if (cterm_normal_bg_color == 0)
    cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;

    /* set termcap codes to current text attributes */
    update_tcap(g_attrCurrent);

    GetConsoleCursorInfo(g_hConOut, &g_cci);
    GetConsoleMode(g_hConIn,  &g_cmodein);
    GetConsoleMode(g_hConOut, &g_cmodeout);

#ifdef FEAT_TITLE
    SaveConsoleTitleAndIcon();
    /*
     * Set both the small and big icons of the console window to Vim's icon.
     * Note that Vim presently only has one size of icon (32x32), but it
     * automatically gets scaled down to 16x16 when setting the small icon.
     */
    if (g_fCanChangeIcon)
    SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
#endif
Run Code Online (Sandbox Code Playgroud)

因此,它只是保存控制台信息(包括标题和图标),然后在退出时再次恢复它.

不幸的是,Console该类不提供对屏幕缓冲区内容的访问,因此要做到这一点,您需要P/Invoke到相关的Win32函数.

或者,Win32控制台实际上支持多个屏幕缓冲区,这可能是一种更简单的方法来实现它 - 而不是复制现有的屏幕缓冲区,只需创建一个新CreateConsoleScreenBuffer缓冲区,并将该缓冲区设置为当前使用的缓冲区SetConsoleActiveScreenBuffer.Console遗憾的是,该类不支持多个屏幕缓冲区,因此您需要P/Invoke才能执行此操作.此外,Console该类始终写入在启动应用程序时处于活动状态的屏幕缓冲区,因此如果您换出活动屏幕缓冲区,Console该类仍将写入旧屏幕缓冲区(不再可见) - 以获取在此期间,您需要P/Invoke所有控制台访问权限,请参阅在.NET中使用控制台屏幕缓冲区.