Skip to content
systemcoding.dev
GPU

Open a Window and Handle Keyboard Input With GLFW

Open a window with GLFW 3.4 in C, run an event loop, and read the keyboard through a key callback and through polling with glfwGetKey.

7 min read
Summarize in AI
Flat illustration of a GPU die of compute units with one thread block lit, with the C, Khronos Group and NVIDIA logos.

Every graphics program starts the same way: ask the operating system for a window, keep it alive, and listen for the user. GLFW is a small C library that does exactly that on Windows, macOS and Linux, and this post is the shortest complete path through it. You will install GLFW 3.4, open a window, write the event loop, and read the keyboard in the two ways the library offers. It is the first rung of the windowing and input guide, and every later post on this site that draws something assumes the loop you build here.

What GLFW is

GLFW stands for Graphics Library Framework. It creates windows, gives you an OpenGL or Vulkan context to draw into, and delivers input from the keyboard, mouse and gamepads. It does not draw anything itself. Think of it as the doorway: the window is the frame, and OpenGL or Vulkan is the paint you apply once the frame exists. Version 3.4 is the current stable line and it supports Windows, macOS, and both X11 and Wayland on Linux.

Two terms recur below. An event loop is a loop that repeatedly asks the operating system whether anything happened, such as a key press, a click or a resize. A callback is a function you write and hand to a library, so that the library calls it when something happens.

Install GLFW

On Debian or Ubuntu, install the development package, which includes the headers:

Shell
sudo apt install libglfw3-dev

On macOS with Homebrew:

Shell
brew install glfw

On Windows, use vcpkg, which builds the library and registers it with CMake:

Shell
vcpkg install glfw3

You also need a C compiler and CMake 3.20 or later. Nothing else is required for this post, because we will not draw yet.

The smallest window

Create a file named window.c. Read it from top to bottom, because the order of the calls is the lesson:

window.cc
#include <GLFW/glfw3.h>
#include <stdio.h>

static void on_error(int code, const char* description) {
    fprintf(stderr, "GLFW error %d: %s\n", code, description);
}

int main(void) {
    glfwSetErrorCallback(on_error);

    if (!glfwInit()) {
        return 1;
    }

    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);

    GLFWwindow* window = glfwCreateWindow(800, 600, "My first window", NULL, NULL);
    if (!window) {
        glfwTerminate();
        return 1;
    }

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}

Walking through it. glfwSetErrorCallback comes first because GLFW reports problems only through that callback, and it may be called before glfwInit for exactly this reason. glfwInit loads the platform's window system, and it returns GLFW_FALSE when that fails, for example when no display is available. glfwWindowHint sets a property of the next window, and GLFW_NO_API says "do not create an OpenGL context", since this program draws nothing. glfwCreateWindow takes the width and height in screen coordinates, the title, a monitor for fullscreen (null means windowed) and a window to share resources with (null means none). It returns a pointer, or null on failure.

The loop runs until the user closes the window. glfwWindowShouldClose returns true after the user clicks the close button, and glfwPollEvents is the event loop's heartbeat: it asks the operating system for pending events, calls your callbacks for them and returns immediately. A window whose loop never calls it appears frozen, and the operating system may mark it as not responding.

The last two lines release the window and shut the library down.

Build and run

Write a minimal CMakeLists.txt:

CMakeLists.txtcmake
cmake_minimum_required(VERSION 3.20)
project(window C)

find_package(glfw3 3.4 REQUIRED)

add_executable(window window.c)
target_link_libraries(window PRIVATE glfw)

Then configure, build and run:

Shell
cmake -S . -B build
cmake --build build
./build/window

A window titled "My first window" opens at 800 by 600 and stays until you close it. The program prints nothing, and on success the exit status is 0.

If the window does not open, the error callback prints the reason. On a machine without a display, which includes a plain SSH session, you see the following, and the fix is to run the program inside a desktop session:

Text
GLFW error 65550: Failed to detect any supported platform

Read the keyboard with a callback

The first way to read keys is the key callback. You write a function with a fixed signature and register it on the window. GLFW calls it once for every key event:

key_callback.cc
static void on_key(GLFWwindow* window, int key, int scancode, int action, int mods) {
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
        glfwSetWindowShouldClose(window, GLFW_TRUE);
    }
    if (action == GLFW_PRESS) {
        printf("pressed key %d\n", key);
    }
}

The parameters carry everything about the event. key is a layout-based key token, such as GLFW_KEY_A, whose value equals the ASCII code for letters and digits. scancode is a platform-specific number for the physical key. action is one of three values: GLFW_PRESS when the key goes down, GLFW_RELEASE when it comes up, and GLFW_REPEAT when the operating system's auto-repeat fires while the key is held. mods is a bit field that tells you whether Shift, Control, Alt or Super were down.

Register it after creating the window, and add #include <stdio.h> for printf:

register.cc
glfwSetKeyCallback(window, on_key);

Press Escape and the window closes, because the callback sets the close flag and the loop condition becomes false on the next test. Press A, then B, then the space bar, and the program prints the key codes, which for letters are the uppercase ASCII values:

Text
pressed key 65
pressed key 66
pressed key 32

Key 65 is GLFW_KEY_A, 66 is GLFW_KEY_B and 32 is GLFW_KEY_SPACE.

To react to modifiers, test the bits in mods. Quit on Ctrl+Q:

modifiers.cc
if (key == GLFW_KEY_Q && action == GLFW_PRESS && (mods & GLFW_MOD_CONTROL)) {
    glfwSetWindowShouldClose(window, GLFW_TRUE);
}

Use & to test one bit, and compare with == only when you want an exact combination, because holding Caps Lock or Num Lock sets additional bits on some platforms if you enable lock key mods.

Read the keyboard by polling

The second way is to ask for the current state of a key whenever you want it. That fits actions that last as long as a key is held, such as moving a character:

polling.cc
float x = 0.0f;
double previous = glfwGetTime();

while (!glfwWindowShouldClose(window)) {
    double now = glfwGetTime();
    float dt = (float)(now - previous);
    previous = now;

    glfwPollEvents();

    if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) x += 2.0f * dt;
    if (glfwGetKey(window, GLFW_KEY_LEFT)  == GLFW_PRESS) x -= 2.0f * dt;
}

glfwGetKey returns GLFW_PRESS or GLFW_RELEASE, and it never returns GLFW_REPEAT. The movement is multiplied by dt, the seconds since the previous frame, so it advances 2 units per second regardless of how fast the loop runs. A loop that adds a fixed amount per iteration runs faster on a faster machine. If you hold the right arrow for exactly 0.5 seconds, x ends near 1.0.

Polling has one weakness. If the user presses and releases a key between two checks, the loop never sees it. For one-shot actions such as "jump" or "toggle menu", use the callback. Reserve polling for state that you sample every frame.

Choose between them

NeedUseWhy
One-time action (quit, toggle, shoot)Key callback with GLFW_PRESSNever misses a quick tap
Continuous action (walk, steer)glfwGetKey each frameThe state is available when you update
Typed textCharacter callback, not keysLayout and shift state are applied for you
Physical key positionscancodeDoes not move with the keyboard layout

The character callback, glfwSetCharCallback, is the right tool for a text field, because key tokens know nothing about Shift, dead keys or input methods. The other three rows are covered above.

Window title as a debugger

Early in a graphics program you have no text on screen, and printing to the terminal every frame floods it. The window title is a convenient status line, because you can update it cheaply:

title.cc
char title[64];
snprintf(title, sizeof title, "x = %.2f", x);
glfwSetWindowTitle(window, title);

With x at 1.0, the title bar reads x = 1.00. Update it once per frame during development and remove it afterward.

Mistakes beginners make

Forgetting glfwPollEvents makes the window freeze and the close button stop working. Calling any GLFW function before glfwInit succeeds is undefined, apart from the few that the manual lists as allowed, such as glfwSetErrorCallback. Using the key value to read typed characters gives the wrong result on non-US layouts. Ignoring the return value of glfwCreateWindow leads to a null-pointer crash on the next line, and this crash is common on machines whose drivers are missing. And leaving the window running without ever setting the close flag from the keyboard makes the program hard to quit during testing, so bind Escape early.

The functions and constants above are defined in the GLFW input guide and the GLFW window guide.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.