Screenshot of a specific c / GTK window

This is the piece of code that creates the window:

#include <gtk/gtk.h> static GtkWidget* createWindow() { GtkWidget *window; window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_default_size(GTK_WINDOW(window), 800, 600); gtk_widget_set_name(window, "GtkLauncher"); g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL); return window; } int main(int argc, char* argv[]) { GtkWidget *main_window; gtk_init(&argc, &argv); if (!g_thread_supported()) g_thread_init(NULL); main_window = createWindow(); gtk_widget_grab_focus(main_window); gtk_widget_show_all(main_window); gtk_main(); return 0; } 

And here: Convert the GTK script icon to C , I got how to take a screenshot.

gdk_get_default_root_window() will provide me a screenshot of the desktop.

gdk_screen_get_active_window (gdk_screen_get_default()) will give me a screenshot of any active window.

Is there a way to take a screenshot for the window created in the code above?

+1
source share
1 answer

I think this should do it, although you may need to repeat the main loop after the window is displayed so that it is drawn correctly, in which case you will need one more code (I have not tested this)

 #include <unistd.h> #include <stdio.h> #include <gtk/gtk.h> #include <cairo.h> static GtkWidget* createWindow() { GtkWidget *window; window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_default_size(GTK_WINDOW(window), 800, 600); gtk_widget_set_name(window, "GtkLauncher"); g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL); return window; } int main(int argc, char **argv) { gdk_init(&argc, &argv); GtkWidget *main_window = createWindow(); gtk_widget_show_all(main_window); // may not need this, it also may not be enough either while (gtk_events_pending ()) gtk_main_iteration (); GdkWindow *w = GDK_WINDOW(main_window); gint width, height; gdk_drawable_get_size(GDK_DRAWABLE(w), &width, &height); GdkPixbuf *pb = gdk_pixbuf_get_from_drawable(NULL, GDK_DRAWABLE(w), NULL, 0,0,0,0,width,height); if(pb != NULL) { gdk_pixbuf_save(pb, "screenshot.png", "png", NULL); g_print("Screenshot saved to screenshot.png.\n"); } else { g_print("Unable to get the screenshot.\n"); } return 0; } 

If this does not work, you will have to move the screenshot to an event handler that connects to a specific event (I'm not sure if window-state-event likely, then you need to look at the event to find out when to take a screenshot)

+1
source

Source: https://habr.com/ru/post/897849/


All Articles