Adam Zbudniewek
Adam Zbudniewek

Reputation: 117

Terminate PROGRAM whenever key press

I'm trying to just stop my program whenever ESC Key is pressed.

For example i have code like this :

char key;
char msg[20];
printf("\n\n\t\t     press escape to quit\n\n");
do {
    key = _getch();

    if (key == ESC) {
        printf("Key: ESCAPE");
        putchar('\n');

    }
    else {
        printf("Key: %c", key);
        putchar('\n');
    }
    Sleep(5000);


} while (key != ESC);

return 0;

And now when i need to exit my program instantly whenever i press ESC is it possible to do? My program gonna exit after 5 sec.. after

Sleep(5000)

All i want to do is exit program instantly when ESC is pressed.

How can i do that?

Upvotes: 1

Views: 6053

Answers (3)

Gor
Gor

Reputation: 2908

Why you check key two times in loop ? You can do this with only one check.

What about this ?

int key;
char msg[20];
printf("\n\n\t\t     press escape to quit\n\n");

while(true) {
    key = _getch();
    if(key == ESC) {
        printf("Key: ESCAPE");
        putchar('\n');
        break;
    }

    printf("Key: %c", key);
    putchar('\n');
    Sleep(5000);
}

Upvotes: 0

Amir Ali
Amir Ali

Reputation: 11

Well, you can compare it with it's ASCII code. ASCII code for ESC key is 27.

 char key;
char msg[20];
printf("\n\n\t\t     press escape to quit\n\n");
do {
  key = _getch();

  if (key == 27) {
      printf("Key: ESCAPE");
      putchar('\n');
  }
  else {
      printf("Key: %c", key);
      putchar('\n');
      Sleep(5000);
  }

} while (key != 27);

Upvotes: 1

D. Mika
D. Mika

Reputation: 2808

The simplest way is to move the sleep call into the else part so it is executed only if a key <> 'ESC' is pressed.

char key;
char msg[20];
printf("\n\n\t\t     press escape to quit\n\n");
do {
    key = _getch();

    if (key == ESC) {
        printf("Key: ESCAPE");
        putchar('\n');
    }
    else {
        printf("Key: %c", key);
        putchar('\n');
        Sleep(5000);
    }

} while (key != ESC);

return 0;

Upvotes: 1

Related Questions