GTK4: Display text on label and quit via ESCAPE

2023-10-12

Type ESCAPE to close the window.

Source code

#include <gtk/gtk.h>

static gboolean key_pressed(GtkWidget* window, guint keyval, guint keycode, GdkModifierType state, GtkEventControllerKey* eventcontroller) {
	if (keyval == GDK_KEY_Escape) {
		gtk_window_destroy(GTK_WINDOW(window));
	}
	return TRUE;
}

static void activate(GtkApplication* app) {
	GtkWindow* window = GTK_WINDOW(gtk_application_window_new(app));
	gtk_window_set_default_size(window, 200, 100);
	GtkWidget* label = gtk_label_new("Hello world!");
	gtk_window_set_child(window, label);
	GtkEventController* event_controller = gtk_event_controller_key_new();
	g_signal_connect_object(event_controller, "key-pressed", G_CALLBACK(key_pressed), window, G_CONNECT_SWAPPED);
	gtk_widget_add_controller(GTK_WIDGET(window), event_controller);
	gtk_window_present(window);
}

int main(int argc, char* argv[]) {
	g_autoptr(GtkApplication) app = gtk_application_new(NULL, 0);
	g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
	return g_application_run(G_APPLICATION(app), argc, argv);
}

Compiling

Compile with:

cc $(pkg-config --cflags gtk4) main.c $(pkg-config --libs gtk4)

Executing

Execute program with:

./a.out