GTK+编程入门(2)—响应GTK+的信号(2015-7-24)
分类:GTK+
在这之前,先来看一个对上一个简单程序的改进程序gtk.c。
#include <gtk/gtk.h>
static void hello(GtkWidget *widget, gpointer data){
/* 输出信息 */
g_printf("Hello World!\n");
}
static gboolean delete_event(GtkWidget *widget, GdkEvent *event, gpointer data){
g_printf("delete event occurred.\n");
/* 如果返回FALSE,GTK+会发出一个“destroy”信号 */
return TRUE;
}
static void destroy(GtkWidget *widget, gpointer data){
/* 输出构件的名字 */
g_printf("%s :exit!\n", gtk_widget_get_name(widget));
/* 退出主循环 */
gtk_main_quit();
}
int main(int argc, char *argv[])
{
GtkWidget *window;
GtkWidget *button;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
/* 注册回调函数 */
g_signal_connect(window, "delete-event", G_CALLBACK(delete_event), NULL);
g_signal_connect(window, "destroy", G_CALLBACK(destroy), NULL);
/* 设置窗口边距 */
gtk_container_set_border_width(GTK_CONTAINER(window), 10);
/* 设置构件名称 */
gtk_widget_set_name(GTK_WIDGET(window), "MainWindow");
/* 创建一个按钮 */
button = gtk_button_new_with_label("Hello World!");
/* 注册单击按钮事件的回调函数 */
g_signal_connect(button, "clicked", G_CALLBACK(hello), NULL);
g_signal_connect_swapped(button, "clicked", G_CALLBACK(gtk_widget_destroy), window);
/* 把构件添加到窗口内 */
gtk_container_add(GTK_CONTAINER(window), button);
/* 显示按钮 */
gtk_widget_show(button);
/* 显示窗口 */
gtk_widget_show(window);
/* 进入GTK+主循环 */
gtk_main();
return 0;
}
它的编译和运行:
biantiao@lazybone1994-ThinkPad-E430:~/sh/GTK+$ gcc -o ex_gtk ex_gtk.c `pkg-config --cflags --libs gtk+-3.0`
biantiao@lazybone1994-ThinkPad-E430:~/sh/GTK+$ ./ex_gtk
Hello