C ++程序应在按下"esc"后立即退出 [英] The C++ program should exit as soon as he presses 'esc'

查看:208
本文介绍了C ++程序应在按下"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;

,我希望该程序在他按'esc'键时立即退出.而且,在按下'esc'键之后,用户也不必按下'enter'键.那怎么办呢?

and I want the program to exit as soon as he presses 'esc' key. And also the user should not have to press the 'enter' key after pressing the 'esc' key. So how to do that??

推荐答案

在Windows中,您可以使用Windows API来完成. GetAsyncKeyState(VK_ESCAPE)帮助您检查是否按了Escape键.您可以尝试这样的事情:

In Windows you can do it using Windows API. GetAsyncKeyState(VK_ESCAPE) helps you to check if Escape is pressed. 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 . Another solutions for this problem are also provided in that question answer from the link.

检测Esc密钥的方法也应该起作用(但是,我没有对其进行正确的测试):

That way of detecting Esc key should also work (however, I didn't test it properly):

#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;
}

这篇关于C ++程序应在按下"esc"后立即退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆