RSS
 

gnome gtk system-tray in C

16 Feb

I was looking for a simple tutorial on how to make system tray icon in C. Well i found this page and tried the example. Just needed to add <gtk/gtk.h> to the include and it compiled and worked just fine. I am adding it here so

  1.  it's easier for me to find when i actually need it again,
  2. sites tend to disappear on the net, so this is my backup copy.

Save the following code into main.c file.

#include <gtk/gtk.h>

void tray_icon_on_click(GtkStatusIcon *status_icon,
                        gpointer user_data)
{
        printf("Clicked on tray icon\n");
}

void tray_icon_on_menu(GtkStatusIcon *status_icon, guint button,
                       guint activate_time, gpointer user_data)
{
        printf("Popup menu\n");
}

static GtkStatusIcon *create_tray_icon() {
        GtkStatusIcon *tray_icon;

        tray_icon = gtk_status_icon_new();
        g_signal_connect(G_OBJECT(tray_icon), "activate",
                         G_CALLBACK(tray_icon_on_click), NULL);
        g_signal_connect(G_OBJECT(tray_icon),
                         "popup-menu",
                         G_CALLBACK(tray_icon_on_menu), NULL);
        gtk_status_icon_set_from_icon_name(tray_icon,
                                           GTK_STOCK_MEDIA_STOP);
        gtk_status_icon_set_tooltip(tray_icon,
                                    "Example Tray Icon");
        gtk_status_icon_set_visible(tray_icon, TRUE);
        return tray_icon;
}

int main(int argc, char **argv) {
        GtkStatusIcon *tray_icon;

        gtk_init(&argc, &argv);
        tray_icon = create_tray_icon();
        gtk_main();

        return 0;
}

You compile the app with the following

gcc main.c -o tray-icon `pkg-config --cflags --libs gtk+-2.0`

Then launch it ./tray-icon

You should see a gray "stop" box appear in the tray. Easy as that.

Leave a Reply

Comments are closed