按Enter键后,ReadConsoleInput只读取第一个符号

时间:2017-04-28 23:09:36

标签: c++ qt winapi

对不起我的英语,但我无法解决问题。现在我正在编写远程控制台。它使用QTcpSocket和函数与Windows控制台一起工作。几乎完美的工作,但是当我尝试从控制台读取时,我需要先按Enter键,然后才会读到我的第一封信。如果我想输入第二个字母,我需要再次按Enter键。我怎样才能阅读我写的每一封信? 这是我的构造函数:

FreeConsole();

    dwProcessId = 0 ;
    dwErrorId = 0;
    std::wstring path = L"cmd.exe";

    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    ZeroMemory(&pi, sizeof(pi));

    si.cb = sizeof(si);

    SECURITY_ATTRIBUTES security = {
       sizeof(security), NULL, TRUE
     };

    if(CreateProcess(NULL, (LPWSTR)path.c_str(), NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
    {
        dwProcessId = pi.dwProcessId;
    }
    else
    {
        dwErrorId = GetLastError();
        printf("CreateProcess failed (%d).\n", dwErrorId);
        return;
    }

    Sleep(1000);

    if(!AttachConsole(pi.dwProcessId))
    {
        dwErrorId = GetLastError();
        printf( "AttachConsole failed (%d).\n", dwErrorId);
        return;
    }

这里我遇到问题的功能:

int Console::readInputFromConsole(DataIn& data)
{
    data.inputRecords.resize(40);

    HANDLE inputHandle = GetStdHandle(STD_INPUT_HANDLE);
    DWORD events = 0;
    DWORD unread = 0;

    DWORD fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
    //fdwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
    BOOL bMode = SetConsoleMode(inputHandle, fdwMode);
    if(!bMode)
    {
        std::runtime_error("error with mode");
    }

    Sleep(20);
    BOOL statusUnread = TRUE;
    statusUnread = GetNumberOfConsoleInputEvents(inputHandle, &unread);
    if(!statusUnread)
        throw std::runtime_error("GetNumberOfConsoleInputEvents failed.");

    data.inputRecords.resize(unread);

    BOOL statusRead = TRUE;
    statusRead = ReadConsoleInput(inputHandle, &data.inputRecords[0], unread, &events);
    if(!statusRead)
        throw std::runtime_error("ReadConsoleInput failed.");

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &data.consoleScreenBufferInfo);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

我解决了问题。我刚在客户端计算机上创建了不必要的进程。这是非常愚蠢的,但这样我就试着在新窗口中开始处理。