如何使用g_timeout_add?

use*_*544 3 c gtk timeout button

我正在用 GTK 和 Glade 用 C 语言编写一个程序,用于串行通信。我在使用 g_timeout_add 时遇到问题。例如,我有一个serial_data()包含串行数据的函数,并且有一个按钮处理程序on_update_button_clicked()。所以到目前为止,我已经做到了,如果update button单击,则gtk_timeout应该运行。但它只运行一次。

on_update_button_clicked(GtkButton *Update_Button)
{
     //2nd argument is serial_data function which contain actual data    
     g_timeout_add(250,serial_data,NULL); 
}
Run Code Online (Sandbox Code Playgroud)

我哪里遗漏了重点?

我还有另一个按钮stop button。所以我希望单击timeout时应该停止。stop button handler怎么做。??

timeout还有一个问题要问,我想像计数器一样统计运行的次数。这样我就可以显示计数器的数字。这怎么可能。?请帮忙谢谢。

jac*_*111 6

从文档来看,该函数被重复调用,直到返回 FALSE。您可以on_update_button使用布尔参数进行调用,以切换超时调用,使其不再被连续调用,在参数计算结果为 时将其设置为运行,并使用if 参数为TRUE来删除线程。这是一个演示:g_source_remove(threadID)FALSE

// compiling with:  gcc test.c `pkg-config --cflags gtk+-3.0` `pkg-config --libs gtk+-3.0` -o test
#include <stdio.h>
#include <gtk/gtk.h>
#include <glib/gi18n.h>

guint threadID = 0;
guint serial_counter = 0;

static gboolean
serial_data (gpointer user_data)
{
    // do something
    printf("counter: %d\n", serial_counter);
    serial_counter++;
    return user_data;
}

static void
on_update_button_clicked (GtkButton* button, gpointer user_data)
{
    if (user_data == 1)
    {
        threadID = g_timeout_add(250, serial_data, user_data);
    }
    else if (user_data == 0)
    {
        g_source_remove(threadID);
        threadID = 0;   
    }
}

int
main (int argc, char *argv[])
{
    GtkWidget *window;
    gtk_init (&argc, &argv);
    GtkWidget *update_button;
    GtkWidget *stop_button;
    GtkWidget *box;

    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title (GTK_WINDOW (window), "test.c");

    box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);

    update_button = gtk_button_new_with_label (_("Update"));
    stop_button = gtk_button_new_with_label (_("Stop"));

    gtk_box_pack_start (GTK_BOX (box), update_button, FALSE, FALSE, 0);
    gtk_box_pack_start (GTK_BOX (box), stop_button, FALSE, FALSE, 0);

    gtk_container_add (GTK_CONTAINER (window), box);

    g_signal_connect (update_button, "clicked", G_CALLBACK (on_update_button_clicked), 1);
    g_signal_connect (stop_button, "clicked", G_CALLBACK (on_update_button_clicked), 0);
    g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
    gtk_widget_show_all (window);

    gtk_main ();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)