简体   繁体   English

C ++程序应在按下“ esc”后立即退出

[英]The C++ program should exit as soon as he presses 'esc'

I have a program in which there is a code which looks something like this: 我有一个程序,其中有一个看起来像这样的代码:

int Element[15];
cout << "Enter name/symbol of the Element: ";
cin >> Element;

and I want the program to exit as soon as he presses 'esc' key. 我希望该程序在他按“ Esc”键时立即退出。 And also the user should not have to press the 'enter' key after pressing the 'esc' key. 而且,用户在按下“ Esc”键后也不必按下“ Enter 键。 So how to do that?? 那么该怎么做呢?

In Windows you can do it using Windows API. 在Windows中,您可以使用Windows API进行操作。 GetAsyncKeyState(VK_ESCAPE) helps you to check if Escape is pressed. GetAsyncKeyState(VK_ESCAPE)帮助您检查是否按了Escape键。 You can try something like this: 您可以尝试如下操作:

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

using namespace std;

int main() {

  int Element[15];
  HANDLE h;

  do {  
    h = GetStdHandle(STD_INPUT_HANDLE);
    if(WaitForSingleObject(h, 0) == WAIT_OBJECT_0) {
      cout << "Enter name/symbol of the Element: ";
      cin >> Element;
    }
  } while(GetAsyncKeyState(VK_ESCAPE)==0);

  return 0;
}

I had the same problem and solved it that way above. 我遇到了同样的问题,并以上述方式解决了这个问题。 This question helped me a lot (the handling idea is from the accepted answer): C++ how do I terminate my programm using ESC button . 这个问题对我有很大帮助(处理想法来自公认的答案): C ++如何使用ESC按钮终止程序 Another solutions for this problem are also provided in that question answer from the link. 链接中的问题答案中也提供了此问题的另一种解决方案。

That way of detecting Esc key should also work (however, I didn't test it properly): 这种检测Esc密钥的方法也应该起作用(但是,我没有对其进行正确测试):

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

using namespace std;

int main() {
  int c = _getcha();
  while(c != 27) {
    // do stuff
    c = _getcha();
  }

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM