GtkClipboard is a wonderful (if somewhat recent) addition to GTK. As you would expect, it allows users to pass data between your application and other GTK applications via the X11 clipboard (and vice versa). A common past annoyance with the clipboard under linux is that data stored disappeared from the clipboard when the application which set the data terminated. No longer so, thanks to gtk_clipboard_store and the GNOME Clipboard Daemon.

Now, tutorials on GtkClipboard are a little sparse and the documentation seems to leave a few questions unanswered, so here’s a quick and dirty primer on passing text data between your GTK applications using GtkClipboard.

Python

import pygtk
pygtk.require('2.0')
import gtk

# get the clipboard
clipboard = gtk.clipboard_get()

# set the clipboard text data
clipboard.set_text('Hello!')

# make our data available to other applications
clipboard.store()

Ruby

require 'gtk2'

# initialize Ruby's GTK bindings
Gtk.init

# get the clipboard
clipboard = Gtk::Clipboard.get(Gdk::Selection::CLIPBOARD)

# set the text. Ruby-Gnome2 also provides a text= setter
clipboard.set_text('Hello, World')

# make the clipboard data available to external applications
clipboard.store

C

#include 
#include 
#include 

int main (int argc, char **argv) {
    const char *message = "Hello, World";

    /* initialize GTK */
    gtk_init (&argc, &argv);

    /* set the clipboard text */
    gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), message, strlen(message));

    /* store the clipboard text */
    gtk_clipboard_store(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD));

    return 0;
}

You can also use gtk_clipboard_set_image (for Ruby and Python, there are equivalents) to pass GdkPixbuf data to the clipboard. Check the GTK/PyGTK/Ruby-Gnome2 documentation for more details.

It’s actually all quite easy, but I thought it might be nice to see the code in practice.