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 key
if (!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 key
std::cout << "You entered: " << input << std::endl;
input = ""; // Reset input
} else if (key == '\b') { // Backspace key
if (!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 key
if (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 key
if (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;
}
尽情享受吧!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY