我该如何ENABLE_VIRTUAL_TERMINAL_PROCESSING?

时间:2018-10-02 12:04:13

标签: c windows console windows-console

前一段时间,我注意到有一个新的控制台模式UPDATE test_data a SET a.value = (SELECT b.value FROM test_alt c JOIN test_data b ON(c.id2 = b.id) WHERE a.id = c.id1) WHERE a.value IS NULL ,因此我决定尝试一下。这是我的示例代码:

ENABLE_VIRTUAL_TERMINAL_PROCESSING

该代码已成功编译到// File: test1.c #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char * const TEST_STRING = "\x1B[31;1mRed\x1B[0m \x1B[32;1mGreen\x1B[0m \x1B[34;1mBlue\x1B[0m"; void ErrorExit(const char* errorMessage) { puts(errorMessage); exit(1); } int main(int argc, char** argv) { if (argc != 2) { ErrorExit("Usage: program (enable|disable|test|sample)"); } HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE), hOutput = GetStdHandle(STD_OUTPUT_HANDLE); DWORD dwMode; char *cmd = argv[1]; if (!strcmp(cmd, "enable")) { /* GetConsoleMode(hInput, &dwMode); dwMode |= ENABLE_VIRTUAL_TERMINAL_INPUT; SetConsoleMode(hInput, dwMode); */ GetConsoleMode(hOutput, &dwMode); dwMode |= ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING; if (!SetConsoleMode(hOutput, dwMode)) { ErrorExit("SetConsoleMode failed."); } } else if (!strcmp(cmd, "disable")) { /* GetConsoleMode(hInput, &dwMode); dwMode &= ~ENABLE_VIRTUAL_TERMINAL_INPUT; SetConsoleMode(hInput, dwMode); */ GetConsoleMode(hOutput, &dwMode); dwMode &= ~ENABLE_VIRTUAL_TERMINAL_PROCESSING; if (!SetConsoleMode(hOutput, dwMode)) { ErrorExit("SetConsoleMode failed."); } } else if (!strcmp(cmd, "test")) { puts(TEST_STRING); } else if (!strcmp(cmd, "sample")) { SetConsoleTextAttribute(hOutput, 0x0C); printf("Red"); SetConsoleTextAttribute(hOutput, 0x07); printf(" "); SetConsoleTextAttribute(hOutput, 0x0A); printf("Green"); SetConsoleTextAttribute(hOutput, 0x07); printf(" "); SetConsoleTextAttribute(hOutput, 0x09); printf("Blue"); SetConsoleTextAttribute(hOutput, 0x07); printf("\n"); } else { ErrorExit("Invalid command!"); } return 0; } 中,但未按预期工作:

screenshot

我相当确定其他所有内容都正确。我正在运行最新的Windows 10企业版64位版本10.0.17763.1

我也尝试过,但这没什么区别:

test1.exe

那我的代码为什么不起作用(在运行else if (!strcmp(cmd, "test")) { DWORD dwNumber = strlen(TEST_STRING), dwWritten; WriteConsole(hOutput, TEST_STRING, dwNumber, &dwWritten, NULL); puts(""); } 之后以test1 test调用仍然产生垃圾)?

1 个答案:

答案 0 :(得分:1)

问题是,您使用SetConsoleMode()进行的设置仅影响正在运行的进程(和潜在的子进程)。这意味着,它实际上不是命令行窗口的设置,并且不会“传递”给父shell进程。您必须在进行输出之前直接设置它,即:

else if (!strcmp(cmd, "test")) {
    GetConsoleMode(hOutput, &dwMode);
    dwMode |= ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
    if (!SetConsoleMode(hOutput, dwMode)) {
        ErrorExit("SetConsoleMode failed.");
    }
    puts(TEST_STRING);
}

这应该可以正常工作。