View Code
#includeint on_quit_event() { gtk_main_quit(); return 0; } int main(int argc,char *argv[]) { GtkWidget *window; gtk_init(&argc ,&argv); window=gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(G_OBJECT(window) ,"delete_event" ,G_CALLBACK(on_quit_event),NULL); gtk_window_set_title(GTK_WINDOW(window) ,"一个功能完善的窗口"); gtk_window_set_default_size(GTK_WINDOW(window) ,500 ,100); gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); gtk_widget_show(window);gtk_main(); return FALSE; }
讲解下上面的代码,GTK添加事件和一般消息相应机制的编程差不多,无非是注册回调函数。
所以这么多的代码只有2句是关键,第一个就是注册 g_signal_connect(G_OBJECT(window) ,"delete_event" ,G_CALLBACK(on_quit_event),NULL);第二个就是进入消息循环gtk_main();其他都是设置下属性等,然后显示,没记错的话,windows上也是这个顺序!
有了和具体控件挂钩的函数,那么控制这些控件就非常简单了。看消息注册函数,原型是
g_signal_connect()
#define g_signal_connect(instance, detailed_signal, c_handler, data)
Connects a function to a signal for a particular object.
The handler will be called before the default handler of the signal.
| the instance to connect to. |
| a string of the form "signal-name::detail". |
| the to connect. |
| data to pass to c_handler calls. |
Returns : | the handler id |
第一个参数当然是要关联的窗口对象,也不一定是窗口,应该是实例。比如按钮,文本框都行。
第二个参数是要关联的事件名称
第三个就是回调函数了,第四个参数是传递给回调函数的参数
再说下gtk_main()
gtk_main ()
void gtk_main (void);
Runs the main loop until is called. You can nest calls to . In that case will make the innermost invocation of the main loop return.
api reference里已经很清楚了。除非调用gtk_main_quit否则它是不退出的。