MiniLibX Hook Examples
This page will showcase some examples hooks that you can use with MiniLibX.
If you need to find what are hooks for MiniLibX, you can fin more information in the Events and Hooks chapter.
Here under I'll show you some examples hooks showing the most important values and some values that are not described in the documentation.
#include "mlx.h"
#define WINDOW_HEIGHT 720
#define WINDOW_WIDTH 1280
int main(void)
{
/*
* this is the MLX initialisation, I only put it in the example so you can
* better see what I am doing below
*/
t_env *env;
env.mlx = mlx_init();
env.win = mlx_new_window(env.mlx, WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_NAME);
env.img = mlx_new_image(env.mlx, WINDOW_WIDTH, WINDOW_HEIGHT);
env.addr = mlx_get_data_addr(env.img, &env.bits_per_pixel, &env.line_length, &env.endian);
/* end of MLX initialisation */
/* Here I will be declaring the hooks, see below for their implementation.
*/
mlx_hook(env.win, 4, 0, mouse_handler, &env);
// mouse_handler will be called everytime a mouse down event is emitted
mlx_hook(env.win, 2, 1L << 0, key_handler, &env);
// key_handler will be called everytime a key is pressed
mlx_hook(env.win, 17, 1L << 0, close_window, &env);
// close_window is called when we click on the red cross to close the window
mlx_loop_hook(env.mlx, render, &env);
// Since MXL loops over and over again, we can use the mlx_loop_hook
// to execute a function everytime MLX loops over.
mlx_loop(env.mlx);
}Simple key_pressed_handler
Since you can filter if you you want to listen to the keypress or keyrelease event, you can have two different key handlers, you might want to start doing something when we press the space key and stop it only when you release it.

Simple mouse_handler
mlx_loop_hook
This hook will call a function every time through the MLX loop, we can use this to update what we show on screen. That's why I called it render or draw most of the time.
For example, in so-long I use this hook to draw the map based on what changed. I draw the background completely again, to overwrite what was there, and then I redraw the walls and the player, but the player position can change based on keypressed events so the player moves along.
The same way for collectibles, I don't want to draw them again if I already collected them (you can see the example I described here).
Last updated
Was this helpful?