glfwSetKeyCallback
Registers a function GLFW calls once for every key press, release and auto-repeat.
Signature
GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun callback);
How it works
The callback receives five values: the window, key (a GLFW_KEY_* constant), scancode (the raw key number of this keyboard), action and mods.
action is GLFW_PRESS when the key goes down, GLFW_RELEASE when it comes up, and GLFW_REPEAT while it is held (the system's auto-repeat, as in a text editor). mods is a bit mask of the modifiers held at that moment: GLFW_MOD_SHIFT, GLFW_MOD_CONTROL, GLFW_MOD_ALT, GLFW_MOD_SUPER.
Use it for one-shot actions: open a menu, toggle wireframe, take a screenshot.
Parameters
The window to listen to.
Your function, void f(GLFWwindow* window, int key, int scancode, int action, int mods), or NULL.
Return value
The callback that was set before, or NULL.
Tips & pitfalls
Check
action == GLFW_PRESS, or a held key fires your toggle again on every GLFW_REPEAT.For typing text (names, chat) use
glfwSetCharCallback: it knows the keyboard layout, accents and Shift.
Errors
When the call is invalid it does nothing and sets an error, which glGetError returns:
- GLFW_NOT_INITIALIZED
- Called before glfwInit or after glfwTerminate.
Example
1void onKey(GLFWwindow* w, int key, int scancode, int action, int mods) {
2 if (action != GLFW_PRESS) return;
3 if (key == GLFW_KEY_ESCAPE) glfwSetWindowShouldClose(w, GLFW_TRUE);
4 if (key == GLFW_KEY_F) wireframe = !wireframe;
5 if (key == GLFW_KEY_S && (mods & GLFW_MOD_CONTROL)) saveScene();
6}
7
8glfwSetKeyCallback(window, onKey);