Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing wallpaper on Linux programmatically

How would I change the wallpaper on a Linux desktop (using GNOME) within a C/C++ program? Is there a system API to do it?

like image 975
nonpolynomial237 Avatar asked Aug 03 '09 05:08

nonpolynomial237


1 Answers

You could use gconf library to do it. The following sample is a complete program to change background:

// bkgmanage.c
#include <glib.h>
#include <gconf/gconf-client.h>
#include <stdio.h>

typedef enum {
    WALLPAPER_ALIGN_TILED     = 0,
    WALLPAPER_ALIGN_CENTERED  = 1,
    WALLPAPER_ALIGN_STRETCHED = 2,
    WALLPAPER_ALIGN_SCALED    = 3,
    WALLPAPER_NONE            = 4
} WallpaperAlign;

gboolean set_as_wallpaper( const gchar *image_path, WallpaperAlign align )
{
    GConfClient *client;
    char        *options = "none";

    client = gconf_client_get_default();

    // TODO: check that image_path is a file
    if ( image_path == NULL ) options = "none";
    else {
        gconf_client_set_string( client, 
            "/desktop/gnome/background/picture_filename",
            image_path,
            NULL );
        switch ( align ) {
            case WALLPAPER_ALIGN_TILED: options = "wallpaper"; break;
            case WALLPAPER_ALIGN_CENTERED: options = "centered"; break;
            case WALLPAPER_ALIGN_STRETCHED: options = "stretched"; break;
            case WALLPAPER_ALIGN_SCALED: options = "scaled"; break;
            case WALLPAPER_NONE: options = "none"; break;
        }
    }
    gboolean result = gconf_client_set_string( client, 
        "/desktop/gnome/background/picture_options", 
        options,
        NULL);
    g_object_unref( G_OBJECT(client) );

    return result;
}

int main(int argc, const char* argv[])
{
  if ( argc > 1 ) {
    printf( "Setting %s as wallpaper... ", argv[1] );
    if ( set_as_wallpaper( argv[1], WALLPAPER_ALIGN_STRETCHED ) ) printf( "Ok\n" );
    else printf( "Failed\n" );
  } else printf( "Usage: ./bkgmanage <filename>\n" );

  return 0;
}

The source above is based on gthumb project. It could be compiled with the following string:

gcc -Wall -g `pkg-config --libs --cflags glib-2.0 gconf-2.0` bkgmanage.c -o bkgmanage
like image 53
Kirill V. Lyadvinsky Avatar answered Sep 20 '22 11:09

Kirill V. Lyadvinsky