Search code examples
cgtkclipboardx11gtk3

How do I use clipboard in GTK?


How can I, using GtkClipboard, read and write to a clipboard? As an example, please show me how to get the current clipboard content and print it to console.

I tried this to get and print what is currently in the clipboard, but it doesn't work:

GtkClipboard *clip = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
gtk_clipboard_request_text(clip, (GtkClipboardTextReceivedFunc)print_clip, NULL);

Everything compiles without any warnings, but print_clip() function is never reached. Maybe I should use another function, like gtk_clipboard_wait_for_text()? Please help me, what am I supposed to do?

I use Linux/X11, if it matters. Also, I use GTK+3, not GTK+2 or some other release.


Ok, I've got a working example:

#include <gtk/gtk.h>

void clipboard_callback(GtkClipboard *clip, const gchar *text, gpointer data)
{
        g_print("Now we're in clipboard_callback function.\n");
        gtk_main_quit();
}

int main(int argc, char **argv)
{
        gtk_init(&argc, &argv);
        GtkClipboard *clip = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
        gtk_clipboard_request_text(clip, clipboard_callback, NULL);
        gtk_main();
        return 0;
}

The only thing that I need now is to somehow exit clipboard_callback() without calling gtk_main_quit(), since that closes an application.


Solution

  • One should really use gtk_clipboard_wait_for_text() instead of gtk_clipboard_request_text().

    For example, this is how it should be done:

    GtkClipboard *clip = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
    gchar *text = gtk_clipboard_wait_for_text(clip);