GTK的非标准设备事件输入

时间:2019-04-01 12:45:17

标签: c gtk hardware

我将GTK用作硬件(3D打印机)的用户界面。硬件可以根据用户与计算机(而不是GUI)的交互来创建事件。例如,他们可以卸下使开关跳闸的构建板,从而向我的程序发送信号,表明发生了这种情况,但是如何获取gtk_main()来识别此事件已发生?

换句话说,如何获取gtk_main()来监视非标准设备输入事件?

1 个答案:

答案 0 :(得分:0)

您可以使用custom actions提供的GtkApplication

在任何情况下,您都必须自己通过轮询硬件状态或利用更高级的技术(如果可能)来实施监视代码。

/* gcc -o monitor monitor.c $(pkg-config --cflags --libs gtk+-3.0) */

#include <gtk/gtk.h>

static void
startup(GtkApplication *application)
{
    GAction *action;

    /* plate-removed is a custom action */
    action = G_ACTION(g_simple_action_new("plate-removed", NULL));
    g_action_map_add_action(G_ACTION_MAP(application), action);
    g_object_unref(action);

    /* You can connect your callbacks to the GAction::activate signal */
    action = g_action_map_lookup_action(G_ACTION_MAP(application), "plate-removed");
    g_signal_connect_swapped(action, "activate",
                             G_CALLBACK(g_print), "Plate has been removed\n");
}

static gpointer
worker_thread(gpointer user_data)
{
    GApplication *application = G_APPLICATION(user_data);
    for (;;) {
        g_usleep(g_random_int_range(500000, 5000000));
        /* Event occurred: emit the signal */
        g_action_group_activate_action(G_ACTION_GROUP(application),
                                       "plate-removed", NULL);
    }
    return NULL;
}

static gboolean
polling_loop(gpointer user_data)
{
    GApplication *application = G_APPLICATION(user_data);
    if (g_random_int_range(1, 20) == 8) {
        /* Event occurred: emit the signal */
        g_action_group_activate_action(G_ACTION_GROUP(application),
                                       "plate-removed", NULL);
    }
    return G_SOURCE_CONTINUE;
}

static void
activate(GtkApplication *application)
{
    GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_application_add_window(application, GTK_WINDOW(window));
    gtk_widget_show_all(window);

    /* You can use whatever you want to monitor your hardware, in particular
     * a polling loop or a worker thread */
    g_timeout_add(50, polling_loop, application);
    /* g_thread_new("WorkerThread", worker_thread, application); */
}

int
main(int argc, char *argv[])
{
    GtkApplication *application;
    int retval;

    application = gtk_application_new(NULL, G_APPLICATION_FLAGS_NONE);
    g_signal_connect(application, "startup", G_CALLBACK(startup), NULL);
    g_signal_connect(application, "activate", G_CALLBACK(activate), NULL);
    retval = g_application_run(G_APPLICATION(application), argc, argv);
    g_object_unref(application);

    return retval;
}