273. How to set up an application to run in the system tray using GtkStatusIcon - Part 1?

Problem

You would like to set up set up an application to run in the system tray.

Let's suppose we are setting an MP3 player. When the application is first started, an icon will appear in the system tray. Since no music is playing, the icon displayed is the standard Gtk::STOCK_MEDIA_STOP. When the user click on the icon, it will start playing, and we change the icon to the standard Gtk::STOCK_MEDIA_PLAY as shown below:

How to set up an application to run in the system tray using GtkStatusIcon - Part 1?


Solution

  • Setting up the system tray icon is simple with the new widget GtkStatusIcon available in gtk+2.10 and above.
  • In this example, we set the icon using standard stock images with GtkStatusIcon::set_from_stock(). You can view the entire list of stock images here.
  • You can also set tooltips on the icon using GtkStatusIcon::set_tooltip()
  • The signal 'activate' allow us to detect left mouse click.
  • The signal 'popup-menu' allow us to detect right mouse click.

Important Note: This only works for PHP-GTK2 compliled with gtk+ v2.10 and above. If you are using an older version, for linux, you may follow the step-by-step instructions to recompile php-gtk2 with gtk+ v2.10. For windows, please refer to How to install php gtk2 on windows? You may also want to take a look here to see some of the new exciting PHP-GTK2 Functionalities.


Sample Code

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
12   
14   
15   
16   
17   
18   
19   
20   
21   
22   
23   
24   
25   
26   
27   
28   
29   
30   
<?php
$statusicon = new GtkStatusIcon(); // note 1
$statusicon->set_from_stock(Gtk::STOCK_MEDIA_STOP); // note 2
$statusicon->set_tooltip('Left click to PLAY'); // note 3

$player_status = 0;
$statusicon->connect('activate', 'on_activate'); // note 4
$statusicon->connect('popup-menu', 'on_popup_menu'); // note 5

Gtk::main();

function on_activate($statusicon) {
    global $player_status;
    if ($player_status) { // note 6
        $statusicon->set_from_stock(Gtk::STOCK_MEDIA_STOP);
        $statusicon->set_tooltip('Left click to PLAY');
        $player_status = 0;
    } else {
        $statusicon->set_from_stock(Gtk::STOCK_MEDIA_PLAY);
        $statusicon->set_tooltip('Left click to STOP');
        $player_status = 1;
    }
}

function on_popup_menu($statusicon) {
    echo "on_popup_menu\n";
}

?>

Output

As shown above.
 

Explanation

  1. Create a new status icon.
  2. Set the icon.
  3. Set the tooltip.
  4. Track left click.
  5. Track right click
  6. Change the icon according to the current player status.

Note

  • In this Part 1, I have showed the basics of setting up the tray icon.
  • In Part 2, I will show you how to popup a GTK window on left mouse click.
  • In Part 3, I will show you how to popup a menu on right mouse click.

Related Links

Add comment


Security code
Refresh