如何在MFC中使用WriteConsoleInput()?

时间:2013-02-07 05:36:09

标签: c++ c visual-c++ mfc

我可以在控制台应用程序中使用WriteConsoleInput()。但是当我尝试在MFC中使用writeConsoleInput()时,它不会在命令窗口中输入任何内容。这是我的代码。

DWORD WINAPI test(LPVOID lp)
{
    system("edit");
    return 0;
}

void CVirusScanDlg::OnBnClickedFormat()
{
    HANDLE hConIn = GetStdHandle(STD_INPUT_HANDLE);
    HANDLE hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD dwTmp;
    INPUT_RECORD ir[5];

    CreateThread(NULL, 0, test,(LPDWORD)0, 0, &dwTmp);

    Sleep( 1000 );

    ir[0].EventType = KEY_EVENT;
    ir[0].Event.KeyEvent.bKeyDown = TRUE;
    ir[0].Event.KeyEvent.dwControlKeyState = 0;
    ir[0].Event.KeyEvent.uChar.UnicodeChar = 'u';
    ir[0].Event.KeyEvent.wRepeatCount = 1;
    ir[0].Event.KeyEvent.wVirtualKeyCode = 'U';
    ir[0].Event.KeyEvent.wVirtualScanCode = MapVirtualKey('U', MAPVK_VK_TO_VSC);

    ir[1].EventType = KEY_EVENT;
    ir[1].Event.KeyEvent.bKeyDown = TRUE;
    ir[1].Event.KeyEvent.dwControlKeyState = 0;
    ir[1].Event.KeyEvent.uChar.UnicodeChar = 'c';
    ir[1].Event.KeyEvent.wRepeatCount = 1;
    ir[1].Event.KeyEvent.wVirtualKeyCode = 'C';
    ir[1].Event.KeyEvent.wVirtualScanCode = MapVirtualKey('C', MAPVK_VK_TO_VSC);

    ir[2].EventType = KEY_EVENT;
    ir[2].Event.KeyEvent.bKeyDown = TRUE;
    ir[2].Event.KeyEvent.dwControlKeyState = 0;
    ir[2].Event.KeyEvent.uChar.UnicodeChar = 'i';
    ir[2].Event.KeyEvent.wRepeatCount = 1;
    ir[2].Event.KeyEvent.wVirtualKeyCode = 'I';
    ir[2].Event.KeyEvent.wVirtualScanCode = MapVirtualKey('I', MAPVK_VK_TO_VSC);

    ir[3].EventType = KEY_EVENT;
    ir[3].Event.KeyEvent.bKeyDown = TRUE;
    ir[3].Event.KeyEvent.dwControlKeyState = 0;
    ir[3].Event.KeyEvent.uChar.UnicodeChar = VK_RETURN;
    ir[3].Event.KeyEvent.wRepeatCount = 1;
    ir[3].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
    ir[3].Event.KeyEvent.wVirtualScanCode = MapVirtualKey(VK_RETURN, MAPVK_VK_TO_VSC);

    ir[4].EventType = KEY_EVENT;
    ir[4].Event.KeyEvent.bKeyDown = FALSE;
    ir[4].Event.KeyEvent.dwControlKeyState = 0;
    ir[4].Event.KeyEvent.uChar.UnicodeChar = VK_RETURN;
    ir[4].Event.KeyEvent.wRepeatCount = 1;
    ir[4].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
    ir[4].Event.KeyEvent.wVirtualScanCode = MapVirtualKey(VK_RETURN, MAPVK_VK_TO_VSC);

    dwTmp = 0;
    WriteConsoleInput(hConIn, ir, 5, &dwTmp);
    //FlushConsoleInputBuffer(hConIn);
    //WriteConsole(hConIn, "uci\n", 5, &dwTmp, NULL);
    //printf(" dwTmp = %d ", dwTmp);

    Sleep(1000);

  //return 0;
}

当我运行此代码时,它不会在命令窗口中输入任何内容。如何在MFC中使用WriteConsoleInput()?

1 个答案:

答案 0 :(得分:2)

问题不在于MFC本身。问题是GUI应用程序没有控制台I / O ...除非您明确地执行ConsoleAlloc()等。

以下是一些很好的链接: