检查 GTK window 是否有键盘和鼠标焦点 window C++

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

是否有 GTK3 函数可以检测 window 是否有焦点?我目前正在使用以下代码:

#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;
}

我正在使用

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

我想检测 window 是否聚焦并将其打印到控制台。

有一个函数:gtk_widget_is_focus ()

您需要确保 parents 设置了 "has-focus" 属性。 医生。摘录:

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.)

如果您想在 window 获得焦点时接收事件,请为 enter-notify-event (signal)

注册回调

在链接文档中。在 enter-notify-event 之后只有三点的部分就是你想要的:

The “focus” signal

对不起,我应该第一次提到这个事件。