#include <gtk/gtk.h> #include <stdio.h> #include <stdlib.h> /* *点击了关闭按钮之后的回调函数 *gtk_main_quit();结束main函数循环,退出process *TURE:表示事件已处理禁止进一步传播,从而取消关闭操作; *FALSE:事件消息进一步向上传播,从而关闭窗口 */ gint delete_event( GtkWidget *widget, GdkEvent *event, gpointer data ) { gtk_main_quit ();//如果不要该语句,当return TURE时,程序没有任何反应。return FALSE时,仅关闭窗口,而不会退出程序 return FALSE; } /*helloWorld函数,作用是弹出一个dialog*/ void helloWorld (GtkWidget *wid, GtkWidget *win) { GtkWidget *dialog = NULL; //系统常量GTK_MESSAGE_INFO是在说明我们想要生成info对话框。系统常量GTK_BUTTONS_CLOSE将生成一个”关闭”按钮,最后一个参数是我们想要在对话框中显示的文字。 dialog = gtk_message_dialog_new (GTK_WINDOW (win), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "hello world"); gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_CENTER);//显示在屏幕* gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); } /*nihaoshijie函数,作用是弹出一个dialog*/ void nihaoshijie (GtkWidget *wid, GtkWidget *win) { GtkWidget *dialog = NULL; dialog = gtk_message_dialog_new (GTK_WINDOW (win), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_OK_CANCEL, "nihaoshijie"); gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_CENTER); gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); } /*主函数*/ int main( int argc, char *argv[]) { GtkWidget *window;//定义窗口 GtkWidget *button1;//定义button GtkWidget *button2;//定义button GtkWidget *hbox;//定义hbox gtk_init(&argc, &argv);//初始化 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);//创建标准窗口 gtk_window_set_title (GTK_WINDOW (window), "my frist gtk+ program!");//设置窗口title gtk_window_set_default_size(GTK_WINDOW(window),,);//设置窗口大小 gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); g_signal_connect(G_OBJECT(window),"delete_event",G_CALLBACK(delete_event),NULL);//创建信号连接,点击窗口上“关闭”按钮,调用delete_event函数 hbox = gtk_hbox_new(TRUE,);//创建box gtk_container_add (GTK_CONTAINER (window), hbox);//将box添加到窗口 button1 = gtk_button_new_with_label("hello world!");//创建按钮 g_signal_connect(G_OBJECT(button1),"clicked",G_CALLBACK(helloWorld),NULL);//创建信号连接,clicked button时,调用helloWorld函数 gtk_box_pack_start(GTK_BOX(hbox),button1,TRUE,FALSE,);//将按钮添加到box button2 = gtk_button_new_with_label("nihao shijie!");//创建按钮 g_signal_connect(G_OBJECT(button2),"clicked",G_CALLBACK(nihaoshijie),NULL);//创建信号连接,clicked button时,调用nihaoshijie函数 gtk_box_pack_start(GTK_BOX(hbox),button2,FALSE,FALSE,);//将按钮添加到box //点击窗口上面的关闭按钮时,退出程序。实现的机能跟g_signal_connect(G_OBJECT(window),"delete_event",G_CALLBACK(delete_event),NULL);一样 //g_signal_connect_swapped(G_OBJECT(window),"delete_event",G_CALLBACK(gtk_main_quit),NULL); //显示控件,自顶向下。不然窗口出来了,按钮没出来 gtk_widget_show(button1); gtk_widget_show(button2); gtk_widget_show(hbox); gtk_widget_show(window); gtk_main(); ; }
实现的功能是显示一个窗口,上面显示两个按钮,一个“helloworld”,一个“nihaoshijie”。点击helloworld,弹出一个helloWorld的dialog。