使用c / GTK截取特定窗口的屏幕截图

时间:2011-04-26 07:51:38

标签: c linux gtk screenshot

这是一段创建窗口的代码:

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

在这里:Convert a GTK python script to C,我知道如何拍摄截图。

gdk_get_default_root_window()将为我提供桌面的屏幕截图。

gdk_screen_get_active_window (gdk_screen_get_default())会为我提供任何有效窗口的屏幕截图。

有没有办法在上面的代码中创建窗口的截图?

1 个答案:

答案 0 :(得分:1)

我认为这应该这样做,虽然你可能需要在显示窗口之后迭代主循环以使其正确绘制,在这种情况下你需要更多的代码(我还没有测试过)

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

如果它不起作用,你将不得不将屏幕截图移动到连接到某个事件的事件处理程序(我不确定哪个可能window-state-event然后你必须查看事件来计算何时拍摄截图)