Thread: How can "Esc" button exits the program?

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    54

    How can "Esc" button exits the program?

    Hello,
    How can I exit a C program by pressing escape key? what are the statements of pressing or hitting ESC key?

  2. #2
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    428
    You need to look into ASCII. The ASCII value of escape is 27 and you can compare that if the input is stored into a char.

    Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion

    If you don't know how to get input you can use scanf().

    scanf - C Reference
    Last edited by Lesshardtofind; 01-11-2013 at 03:49 AM.
    Virtual reality hello world http://www.rodneybrothers.com/vr/vrh...rld/index.html in html and javascript.
    Viewable with dodocase, google cardboard, OR, and other compatible VR gear.

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by Lesshardtofind View Post
    You need to look into ASCII. The ASCII value of escape is 27 and you can compare that if the input is stored into a char.
    Could you demonstrate how one would do this in practice? For example, try to get the following program to output the result `27' by pressing Escape at the terminal. Hint: it won't work.

    Code:
    int main(void)
    {
        int c = getchar();
        printf("%d\n", c);
        return 0;
    }
    Why? Because when you type at the terminal window, the terminal is in "cooked" mode and the program won't see any characters that you typed until you press enter. For example, when you press backspace and delete, these are not even seen by the standard input/output system. The same is true for the "Escape" key. In fact, the behaviour of this and other keys in cooked mode depends on the operating system.

    To answer the question, I would recommend using a lower level layer like curses, which can put the terminal into raw mode (keypad mode, in curses terminology). Then use getch() to read the keycode. If it was escape, exit the program. Otherwise, use ungetch() and resume normal operation.

  4. #4
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    428
    Hint: it won't work.
    My appologies I guess one should test a solution before posting it. I use too many high level libraries that sometimes I forget I haven't tested all processes in the low level languages. Thank you for the correction.
    Virtual reality hello world http://www.rodneybrothers.com/vr/vrh...rld/index.html in html and javascript.
    Viewable with dodocase, google cardboard, OR, and other compatible VR gear.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You can include a header file like PDcurses or conio.h, or the Windows API, to tell the program when a key has been pressed. Then read the key, and if it's value is 27, exit.

    The MSDN library will have an example for the Windows API. This is an example you can use ONLY if your compiler supports conio.h (not all do).

    This example is more than you need, but shows the code and logic you need.

    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    
    #define ESC 27
    #define F1 59
    #define F2 60
    #define F3 61
    #define F4 62
    #define F5 63
    #define F6 64
    #define F7 65
    #define F8 66
    #define F9 67
    #define F10 68
    #define HOME 71
    #define UP 72
    #define PAGE_UP 73
    #define LEFT 75
    #define RIGHT 77
    #define END 79
    #define DOWN 80
    #define PAGE_DOWN 81
    
    int main(void) {
    
       char key;
       char msg[20];
       printf("\n\n\t\t     press escape to quit\n\n") ;
       do {
          key = _getch();
          if (key == 0 || key == -32) { 
             key = _getch(); //key code has two keys - read the second one
             switch (key) {
                case F1: memcpy(msg,"F1", sizeof(msg)); break;
                case F2: memcpy(msg,"F2", sizeof(msg)); break;
                case F3: memcpy(msg,"F3", sizeof(msg)); break;
                case F4: memcpy(msg,"F4", sizeof(msg)); break;
                case F5: memcpy(msg,"F5", sizeof(msg)); break;
                case F6: memcpy(msg,"F6", sizeof(msg)); break;
                case F7: memcpy(msg,"F7", sizeof(msg)); break;
                case F8: memcpy(msg,"F8", sizeof(msg)); break;
                case F9: memcpy(msg,"F9", sizeof(msg)); break;
                case F10: memcpy(msg,"F10", sizeof(msg)); break;
                case PAGE_UP: memcpy(msg,"PAGE UP", sizeof(msg)); break;
                case PAGE_DOWN: memcpy(msg,"PAGE DOWN", sizeof(msg)); break;
                case HOME: memcpy(msg,"HOME", sizeof(msg)); break;
                case END: memcpy(msg,"END", sizeof(msg)); break;
                case UP: memcpy(msg,"UP", sizeof(msg)); break;
                case DOWN: memcpy(msg,"DOWN", sizeof(msg)); break;
                case LEFT: memcpy(msg,"LEFT", sizeof(msg)); break;
                case RIGHT: memcpy(msg,"RIGHT", sizeof(msg)); break;
                default:  memcpy(msg,"unknown key", sizeof(msg)); break;
             }
             printf("Key: %s", msg);
             putchar('\n');
             continue;
          }
          if(key == ESC) {
             printf("Key: ESCAPE");
             putchar('\n');
          }
          else {
             printf("Key: %c", key);
             putchar('\n');
          }
       }while (key != ESC); 
    
       return 0;
    }

  6. #6
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    It seems the example will only work on Windows. If you do it with curses then it will work with Windows, Linux, iPhone, etc.

    Code:
    /*
    gcc -Wall -std=gnu99 -o esc_ex esc_ex.c -lpdcurses
    */
    #include <curses.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    #define CTRLC '\003'  // Code for CTRL-C might be different on other systems
    
    void do_endwin(void) {endwin();}
    
    int main(void)
    {
    	// Start curses mode
    	if (initscr() == NULL) {
    		fprintf(stderr, "Could not initialize screen\n");
    		exit(EXIT_FAILURE);
    	}
    	atexit(do_endwin);
    	keypad(stdscr, TRUE);		// raw mode ON
    	noecho();					// echo mode OFF
    	scrollok(stdscr, TRUE);		// scrolling mode ON
    	
    	// Read each character into key and print its description
    	int key;
    	printw("Press some keys on the keyboard to see their keycodes. ESC to exit.\n");
    	refresh();
    	while ((key = getch()) != '\e') {
    		switch(key) {
    		case '\n':
    			printw("Enter");
    			break;
    		case CTRLC:
    			printw("Ctrl-C");
    			break;
    		case KEY_F(1): 
    			printw("F1");
    			break;
    		case KEY_F(2): 
    			printw("F2");
    			break;
    		case KEY_LEFT:
    			printw("Left");
    			break;
    		case KEY_RIGHT:
    			printw("Right");
    			break;
    		case KEY_UP:
    			printw("Up");
    			break;
    		case KEY_DOWN:
    			printw("Down");
    			break;
    		default:
    			if (isprint(key))
    				printw("key with printable character '%c'", key);
    			else
    				printw("key with nonprintable code %d", key);
    			break;
    		}
    		printw("\n");
    		refresh();
    	}
    	printw("You pressed ESC. Ending...\n\n");
    	refresh();
    		
    	// Print message and wait for user to press a key
    	printw("Press any key to end the program...");
    	refresh();
    	getch();
    	exit(EXIT_SUCCESS);
    }
    Last edited by c99tutorial; 01-11-2013 at 07:17 AM.

  7. #7
    Registered User
    Join Date
    Nov 2012
    Posts
    32
    Quote Originally Posted by c99tutorial View Post
    Code:
        while ((key = getch()) != '\e') {
    Is '\e' GNU extension?

  8. #8
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by Shurik View Post
    Is '\e' GNU extension?
    I thought it was standard, but I guess not. Add the following define

    Code:
    #define KEY_ESC '\033'
    and use KEY_ESC instead of '\e'

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. IT policy disabling of "Show Desktop" button
    By hk_mp5kpdw in forum Tech Board
    Replies: 5
    Last Post: 04-16-2010, 12:13 PM
  2. Handle on MSN Messenger's Sign In "button"?
    By jmd15 in forum Windows Programming
    Replies: 3
    Last Post: 07-16-2005, 09:28 PM
  3. How to program a "back" button with MFC
    By 99atlantic in forum Windows Programming
    Replies: 3
    Last Post: 04-26-2005, 08:34 PM
  4. "itoa"-"_itoa" , "inp"-"_inp", Why some functions have "
    By L.O.K. in forum Windows Programming
    Replies: 5
    Last Post: 12-08-2002, 08:25 AM
  5. "CWnd"-"HWnd","CBitmap"-"HBitmap"...., What is mean by "
    By L.O.K. in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2002, 07:59 AM