Grabbing a screenshot with Gdk

From Widget to Pixbuf

Need to grab a screenshot in your program? Or maybe you just need to create an image from an existing GtkWidget. There's an easy way to accomplish both tasks using GdkPixbuf::get_from_drawable();

To use the method you'll need two things - an empty GdkPixbuf and the "drawable" (GdkDrawable) associated with your widget. Most widgets will have a GdkWindow located in $widget->window. You can get the entire screen, however, by using Gdk::get_default_root_window();. Now for the code examples...

Creating a screenshot

<?php
/**
* This comes first because we need to make sure all
* widgets are shown on the screen before we
* take a picture of them
*/
while (Gtk::events_pending())
  {
 
Gtk::main_iteration();
  }

// get the root gdkwindow (entire screen)
$root = Gdk::get_default_root_window();

// get the size of the screen
list($width, $height) = $root->get_size();

// create an empty pixbuf the same size
$pixbuf = new GdkPixbuf(Gdk::COLORSPACE_RGB, TRUE, 8,
 
$width, $height);

// grab a pixbuf from the screen
$pixbuf->get_from_drawable ($root, $root->get_colormap(), 0, 0,
 
0, 0, $width, $height);
?>

Creating a pixbuf of a specific widget

<?php
/**
* remember the widget MUST BE SHOWN AND DRAWN
* and not offscreen or you'll get weird black areas
*/
$widget->show();
while (
Gtk::events_pending())
  {
 
Gtk::main_iteration();
  }

/**
* we'll use allocation information: not every widget has
* its own gdkwindow
*/
$alloc = $widget->allocation;
$pixbuf = new GdkPixbuf(Gdk::COLORSPACE_RGB, TRUE, 8,
 
$alloc->width, $alloc>height);
$pixbuf->get_from_drawable ($widget->window,
 
$widget->window->get_colormap(),
 
$alloc->x, $alloc->y,
 
0, 0,
 
$alloc->width, $alloc->height);
?>

After your pixbuf is created you can save it to a file, or display it in a GtkImage or manipulate it with GdkPixbuf methods- have fun.