在GTK中,如果定时让程序去作某件事,使用g_timeout_add

转载自:http://blog.csdn.net/ustcxiangchun/archive/2009/09/01/4508086.aspx
这个例子的作用就是把当前时间显示到窗口中,即显示了一个实时时钟。
//~~~~~~~ begin of program ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <cairo.h>
#include <gtk/gtk.h>
#include <time.h>

static char buffer[256];
/******************************
*  把buffer显示到窗口中
*  每次画窗口时调用
*/
static gboolean
on_expose_event(GtkWidget *widget,
    GdkEventExpose *event,
    gpointer data)
{
  cairo_t *cr;

  cr = gdk_cairo_create(widget->window);

  cairo_move_to(cr, 30, 30);
  cairo_show_text(cr, buffer);

  cairo_destroy(cr);

  return FALSE;
}
/******************************
*  把当前时间打印到buffer中,并且重画窗口
*  每次timeout后调用,即每秒调用一次
*/
static gboolean
time_handler(GtkWidget *widget)
{
  if (widget->window == NULL) return FALSE;

  time_t curtime;
  struct tm *loctime;

  curtime = time(NULL);
  loctime = localtime(&curtime);
  strftime(buffer, 256, "%T", loctime);

  gtk_widget_queue_draw(widget);
  return TRUE;
}
int
main (int argc, char *argv[])
{

  GtkWidget *window;
  GtkWidget *darea;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

  darea = gtk_drawing_area_new();
  gtk_container_add(GTK_CONTAINER (window), darea);

  g_signal_connect(darea, "expose-event",
      G_CALLBACK(on_expose_event), NULL);   // 每次画窗口时的callback
  g_signal_connect(window, "destroy",
      G_CALLBACK(gtk_main_quit), NULL);

  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_default_size(GTK_WINDOW(window), 170, 100);

  gtk_window_set_title(GTK_WINDOW(window), "timer");
  g_timeout_add(1000, (GSourceFunc) time_handler, (gpointer) window);
  gtk_widget_show_all(window);
  time_handler(window);

  gtk_main();

  return 0;
}
//~~~~~~~ end of program ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

One thought on “在GTK中,如果定时让程序去作某件事,使用g_timeout_add

  1. vodka

    How to compille?

     

    I get two errors:

     

     gcc timer.c `pkg-config gtkmm-3.0 --cflags --libs` 
    timer.c: In function ‘on_expose_event’:
    timer.c:12:31: error: ‘GtkWidget’ has no member named ‘window’
       cr = gdk_cairo_create(widget->window);
                                   ^
    timer.c: In function ‘time_handler’:
    timer.c:24:13: error: ‘GtkWidget’ has no member named ‘window’
       if (widget->window == NULL) return FALSE;
                 ^
    

     

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *