Search code examples
c++gtk

Check if GTK window has keyboard and mouse focus window C++


Is there a GTK3 function that detects if a window has focus? I am currently using the following code:

#include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
GtkWidget *LinuxWindow;
static void buttonMessage(GtkWidget *widget, gpointer data)
{
  g_print("Yay, you clicked me!\n");
}
int main() {
  GtkWidget *Box, *Button;
  int argC = 0;
  char **argV;
  // Setup the window and fixed grid
  gtk_init(&argC, &argV);
  LinuxWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  Box = gtk_fixed_new();
  // Set the title
  gtk_window_set_title(GTK_WINDOW(LinuxWindow), "Title");
  // Setup the window events
  gtk_widget_show_all(LinuxWindow);
  g_signal_connect(G_OBJECT(LinuxWindow), "destroy", G_CALLBACK(gtk_main_quit),
                   NULL);
  // Add controls
  Button = gtk_button_new_with_label("Click Me!");
  g_signal_connect(Button, "clicked", G_CALLBACK(buttonMessage), NULL);
  gtk_fixed_put(GTK_FIXED(Box), Button, 20, 20);
  gtk_fixed_move(GTK_FIXED(Box), Button, 20, 20);
  gtk_widget_set_size_request(Button, 30, 100);
  gtk_container_add(GTK_CONTAINER(LinuxWindow), Box);
  gtk_widget_show_all(LinuxWindow);
  // Create a dialog
  GtkWidget *dialog;
  dialog = gtk_message_dialog_new(
      GTK_WINDOW(LinuxWindow), GTK_DIALOG_DESTROY_WITH_PARENT,
      GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "Hello and welcome to my GTK GUI...", NULL);
  gint ret = gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_destroy(GTK_WIDGET(dialog));
  printf("%i", ret);
  // Add the fixed grid and go the to the main window loop

  gtk_main();

  return 0;
}

I am compiling it using

g++ -std=c++17 -m64 -o gtkTest myGtkApp.cpp -lX11 `pkg-config --cflags gtk+-3.0` `pkg-config --libs gtk+-3.0`

I want to detect if the window is focused and print it to the console.


Solution

  • There is a function: gtk_widget_is_focus ().

    You need to assure parents have the "has-focus" property set. Doc. excerpt:

    gtk_widget_is_focus (GtkWidget *widget);

    Determines if the widget is the focus widget within its toplevel. (This does not mean that the “has-focus” property is necessarily set; “has-focus” will only be set if the toplevel widget additionally has the global input focus.)

    If you want to receive an event when the window is focused then register a callback for the enter-notify-event (signal)

    In the linked doc. there is a section just three points after enter-notify-event that is what you want:

    The “focus” signal

    Sorry, I should have to mention this event the first time.


    Edit for new links from docs.gtk.org: