首页 > 解决方案 > 键盘中断例程 Visual Studio C++ 控制台应用程序

问题描述

我正在使用 VS 2022 Preview 编写 C++ 控制台应用程序。我希望检测键盘敲击并调用我的中断处理函数。我希望快速检测到按键,以防 main 处于长循环中,因此不使用 kbhit()。

我找到了 signal() 但是当检测到 Control-C 时调试器停止。也许这是 IDE 的特性。是否有我应该使用的函数或系统调用?

编辑:我隐约知道线程。我可以生成一个只监视 kbd 的线程,然后在按下键时让它引发(?)中断吗?

标签: keyboardinterruptvisual-c++-2008

解决方案


我能够通过添加一个线程来做到这一点。在目标上,我将有真正的中断来触发我的 ISR,但这对于算法开发来说已经足够接近了。似乎终止线程比它的价值更麻烦,所以我合理化了我正在模拟一个不需要花哨关闭的嵌入式系统。

我决定在虚假的 ISR 中一次只接受一个字符,然后当我看到一个简单的命令行处理器 CR 时,我可以缓冲它们并等待并处理整个字符串。

// Scheduler.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <Windows.h>
#include <iostream>
#include <thread>
#include <conio.h>

void phonyISR(int tbd)
{
    char c;
    while (1)
    {
        std::cout << "\nphonyISR() waiting for kbd input:";
        c = _getch();
        std::cout << "\nGot >" << c << "<";
    }
}

int main(int argc, char* argv[])
{
    int tbd;
    std::thread t = std::thread(phonyISR, tbd);

    // Main thread doing its stuff
    int i = 0;
    while (1)
    {
        Sleep(2000);
        std::cout << "\nMain: " << i++;
    }

    return 0;
}

推荐阅读