GLUT Keyboard Input Handler

Understanding character stroke hooks and special key processing callbacks.

ASCII Keyboard Callback

Standard alphanumeric keyboard inputs are captured using glutKeyboardFunc(myKeyboard). The callback takes the key character and the cursor coordinates at the time of keypress:

void myKeyboard(unsigned char key, int x, int y) {
    if (key == 27) { // ESC key ASCII
        exit(0);
    }
}
                        

Special Function Keys

Non-ASCII strokes (like Arrow keys, F1-F12, PageUp, etc.) do not trigger the standard keyboard callback. Instead, you must register them with glutSpecialFunc(mySpecial):

void mySpecial(int key, int x, int y) {
    switch(key) {
        case GLUT_KEY_LEFT:  xOffset -= 5; break;
        case GLUT_KEY_RIGHT: xOffset += 5; break;
    }
    glutPostRedisplay();
}
                        

Ready to Test Keyboard Interaction?

Launch our interactive visualizer to move objects using arrow keys and catch character ASCII codes.

Launch Keyboard Visualizer →