gpt4 book ai didi

c - GTK 的非标准设备事件输入

转载 作者:行者123 更新时间:2023-11-30 16:19:53 25 4
gpt4 key购买 nike

我使用 GTK 作为硬件(3D 打印机)的用户界面。硬件可以创建事件作为用户与机器(而不是 GUI)交互的结果。例如,他们可以移除构建板,该构建板会触发开关,从而向我的程序发送已发生这种情况的信号,但如何让 gtk_main() 识别该事件已发生?

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

最佳答案

您可以使用custom actionsGtkApplication提供.

在任何情况下,您都必须通过轮询硬件状态或利用更先进的技术(如果可能)自行实现监控代码。

/* 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;
}

关于c - GTK 的非标准设备事件输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55455453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com