10

有没有人有一段代码不windows.h用于在while循环中检查按键。基本上是这段代码,但不必用windows.h它来做。我想在 Linux 和 Windows 上使用它。

#include <windows.h>
#include <iostream>

int main()
{
    bool exit = false;

    while(exit == false)
    {
        if (GetAsyncKeyState(VK_ESCAPE))
        {
            exit = true;
        }
        std::cout<<"press esc to exit! "<<std::endl;
    }

    std::cout<<"exited: "<<std::endl;

    return 0;
}
4

5 回答 5

6
#include <conio.h>
#include <iostream>

int main()
{
    char c;
    std::cout<<"press esc to exit! "<<std::endl;
    while(true)
    {
        c=getch();
        if (c==27)
          break;
    }

    std::cout<<"exited: "<<std::endl;

    return 0;
}
于 2013-04-01T04:26:38.307 回答
2
char c;
while (cin >> c) {
...
}

ctrl-D终止上述循环。只要输入一个字符,它就会继续。

于 2013-04-01T04:14:35.273 回答
2

您最好的选择是创建一个自定义的“GetAsyncKeyState”函数,该函数将使用#IFDEF for windows 和 linux 来选择适当的 GetAsyncKeyState() 或等效项。

没有其他方法可以达到预期的结果,cin 方法有其问题 - 例如应用程序必须处于焦点。

于 2013-04-01T04:23:00.613 回答
-1

//最简单的。

    #include <iostream>
    #include <conio.h>

using namespace std;
    int main()
    {

        char ch;
        bool loop=false;

      while(loop==false)
       {
        cout<<"press escape to end loop"<<endl;
        ch=getch();
        if(ch==27)
        loop=true;
       }
        cout<<"loop terminated"<<endl;
        return 0;
    }
于 2015-10-11T17:11:35.100 回答
-2
//its not the best but it works


#include <vector>
#define WINVER 0x0500
#include <windows.h>
#include <conio.h>
#include <iostream>

int main()
{
char c;
std::cout<<"press esc to exit! "<<std::endl;
while(true)
{

std::cout<<"executing code! , if code stops press any key to     continue or esc to stop"<<std::endl;


 INPUT ip;

// Set up a generic keyboard event.aa
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0; // hardware scan code for key
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;

int lol =   65; //a key
    // Press the "A" key
ip.ki.wVk = lol; // virtual-key code for the "a" key
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));

// Release the "A" key
ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
SendInput(1, &ip, sizeof(INPUT));

    c=getch();
    if (c==27)
      break;
  }

std::cout<<"exited: "<<std::endl;
return 0;
}
于 2016-06-17T18:45:38.433 回答