首页 / 操作系统 / Linux / 在Linux下使用libunique实现单实例
Hello! Here ‘s a fairly simple example of how to create single instance Applications with LibUnique and Gtk +. I took the example in the documentation and changed it to demonstrate how to pass a parameter to the active instance.How to compile:gcc -o uniquesample uniquesample.c `pkg-config --cflags gtk+-2.0 unique-1.0 --libs gtk+-2.0 unique-1.0`How to run it, first launch first instance:# ./uniquesample
Then, launch the others:# ./uniquesample "One App to rule them All"
Here’s the code:#include gtk/gtk.h
#include unique/unique.hstatic UniqueResponse
message_received_cb (UniqueApp *app,
UniqueCommand command,
UniqueMessageData *message,
guint time_,
gpointer user_data)
{
UniqueResponse res; /* get text payload from the unique message data*/
gchar *texto = unique_message_data_get_text (message); /* Get the label widget */
GtkLabel *label = GTK_LABEL (user_data); switch (command)
{
case UNIQUE_ACTIVATE:
{
gtk_label_set_text (GTK_LABEL (label), texto);
res = UNIQUE_RESPONSE_OK;
break;
}
default:
res = UNIQUE_RESPONSE_OK;
break;
} return res;
}static gboolean
delete_event_cb (GtkWidget *widget, GdkEvent *event, gpointer data)
{
gtk_main_quit ();
}int
main (int argc, char *argv[])
{
gtk_init (&argc, &argv); /* Create the UniqueApp Instance */
UniqueApp *app = unique_app_new ("home.myapp", NULL); /* check if there already is an instance running */
if (unique_app_is_running (app))
{
if (argc > 1)
{
/* build a message with the first command line argument */
UniqueMessageData *message = unique_message_data_new();
unique_message_data_set_text (message, argv[1], -1); /* send the message, we don"t care about the response */
unique_app_send_message (app, UNIQUE_ACTIVATE, message); unique_message_data_free (message);
g_object_unref (app);
}
}
else
{
/* this is the first instance */
GtkWidget *window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
GtkWidget *label = gtk_label_new ("UNIQUE INSTANCE"); /* Makes app "watch" a window.
* Every watched window will receive startup notification changes automatically
*/
unique_app_watch_window (app, GTK_WINDOW (window)); /* connect to the signal so we can handle commands and responses
* We are passing the label widget here as user data */
g_signal_connect (G_OBJECT (app), "message-received",
G_CALLBACK (message_received_cb), label); g_signal_connect (G_OBJECT (window), "delete_event",
G_CALLBACK (delete_event_cb), NULL); gtk_widget_set_size_request (GTK_WIDGET (window), 300, 200); gtk_container_add (GTK_CONTAINER (window), label);
gtk_widget_show_all(window); gtk_main (); g_object_unref (app);
} return 0;
}