I am trying to close a GTK window by pressing ⌘ + q on Mac OS or ALT + F4 on Windows.
The code below works fine if I click into the window once – if I do not click, all commands are passed to the underlying terminal. So e.g. if I press ⌘ + q, my Terminal will ask me if I want to close it (the terminal). But as soon as I click into the window using the mouse pointer, I can use ⌘ + q to close this window. It feels weird that the windows do not gain focus on startup, as I feel all my normal applications do gain focus for keyboard inputs on startup.
main.cpp
// Copyright 2017 Sebastian Höffner
#include "gtk/gtk.h"
namespace {
static void cb_key_press(GtkWidget* widget, GdkEventKey* event_key) {
switch (event_key->keyval) {
case GDK_KEY_F4:
if (event_key->state & GDK_MOD1_MASK) {
gtk_main_quit();
}
break;
case GDK_KEY_q: case GDK_KEY_W:
if (event_key->state & GDK_META_MASK) {
gtk_main_quit();
}
break;
}
}
} // namespace
int main(int argc, char** argv) {
gtk_init(&argc, &argv);
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(window, "key-press-event", G_CALLBACK(::cb_key_press), NULL);
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_window_fullscreen(GTK_WINDOW(window));
gtk_window_present(GTK_WINDOW(window));
gtk_main();
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
# Project options
project(gtk_test VERSION 0.1 LANGUAGES CXX C)
find_package(PkgConfig)
pkg_check_modules(GTK gtk+-3.0)
include_directories(${GTK_INCLUDE_DIRS})
link_directories(${GTK_LIBRARY_DIRS})
add_executable(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
target_link_libraries(${PROJECT_NAME} ${GTK_LIBRARIES})
To compile, put both files (CMakeLists.txt
and main.cpp
) into the same directory, and follow these commands:
mkdir build
cd build
cmake ..
make
You can then start the program ./gtk_test
(it is located in build
).
Some more background
I initially started out by modifying the Getting started example but quickly found that using a GtkApplication
seems to be overkill for my application (which basically should only show fullscreen images, thus OpenCV's highgui is not good enough without the Qt backend), so I adapted gtk_window_new(GTK_WINDOW_TOPLEVEL);
which I found on various answers and tutorials.
This answer to How to give keyboard focus to a pop-up Gtk.Window explains how to gain exclusive keyboard access for an application, but I only want to have keyboard focus when I start the application.
UPDATE: Added CMakeLists.txt and removed the generated compilation messages. Added explanations on how to compile and run.