本文主要是介绍windows c++ 不堵塞 监听键盘输入 历史记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
windows c++ 不堵塞 监听键盘输入 支持修改已经输入的内容,并且记录最近30条记录,多了覆盖,通过上下方向按键来显示历史记录
代码如下:
#include <iostream>
#include <windows.h>
#include <vector>
#include <string>int main() {std::vector<std::string> history;int historyIndex = -1;std::string input = "";HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);SetConsoleMode(hInput, ENABLE_WINDOW_INPUT);while (true) {DWORD numEvents;INPUT_RECORD irInBuf[128];DWORD numEventsRead;if (GetNumberOfConsoleInputEvents(hInput, &numEvents) && numEvents > 0) {ReadConsoleInput(hInput, irInBuf, 128, &numEventsRead);for (DWORD i = 0; i < numEventsRead; i++) {if (irInBuf[i].EventType == KEY_EVENT && irInBuf[i].Event.KeyEvent.bKeyDown) {char key = irInBuf[i].Event.KeyEvent.uChar.AsciiChar;if (key == '\r') { // Enter keyif (!input.empty()) {history.insert(history.begin(), input);if (history.size() > 30) {history.pop_back();}}historyIndex = -1;std::cout << std::endl; // Move to a new line after Enter keystd::cout << "You entered: " << input << std::endl;input = ""; // Reset input} else if (key == '\b') { // Backspace keyif (!input.empty()) {input.pop_back();std::cout << "\b \b"; // Move cursor back and erase character}} else if (irInBuf[i].Event.KeyEvent.wVirtualKeyCode == VK_UP) { // Up arrow keyif (historyIndex < static_cast<int>(history.size()) - 1) {historyIndex++;input = history[historyIndex];std::cout << "\r" << std::string(input.length(), ' ') << "\r" << input; // Clear and print new input}} else if (irInBuf[i].Event.KeyEvent.wVirtualKeyCode == VK_DOWN) { // Down arrow keyif (historyIndex >= 0) {historyIndex--;input = historyIndex >= 0 ? history[historyIndex] : "";std::cout << "\r" << std::string(input.length(), ' ') << "\r" << input; // Clear and print new input}} else {input += key;std::cout << key; // Print the entered character}std::cout.flush(); // Flush the output to show in real-time}}}}return 0;
}
尽情享受吧!!!
这篇关于windows c++ 不堵塞 监听键盘输入 历史记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!