介绍 GTK#
[
纯Windows 用户就可以跳过。
也未测试。
]
GTK# 是对流行的跨平台图形用户界面库(GUI)GTK+ 的包装。如果打算构建一个本地应用程序,并想让它运行在非 Windows 平台上,GTK 可能是一个合理的选择。GTK# 的运行类似于 Windows 窗体和 WPF,在 GTK# 中,窗口是基于 Gtk.Window 的,小插件(widgets,相当于控件)是基于 Gtk.Widget 类的。
GTK# 是随 Mono 项目一同发布的,因此,想使用它的最好方法是安装 Mono(http://www.go-mono.com/mono-downloads/download.html)。组成 GTK# 的类分成了四个部分:atk-sharp.dll、gdk-sharp.dll、glib-sharp.dll和 gtk-sharp.dll,要运行本节的示例,需要引用这些 .dll。
在创始 GTK# 小插件之前,必须调用Application.Init() 对 GTK 环境进行初始化;在控件可见之后,要调用 Application.Run() 方法启动事件循环,如果不调用这个方法,窗口和小插件就不会响应用户的单击和其他输入;用户关闭所有的窗口时,需要调用Application.Quit() 关闭事件循环。在这个 GTK# 示例(清单 8-9)中,只有一个窗口,因此,当这个窗口关闭时,就可以退出 GTK 环境了:
// close the event loop when the windowcloses
win.Destroyed.Add(fun _ ->Application.Quit())
使用叫 HBox 或 VBox 的小插件来布局 GTK# 应用程序,这些小插件与 Windows 的类不一样,它可以包含不止一个小插件,排列的方式既可以是水平的,也可以是垂直的。在波音 8-9 中,我们创建了一个 VBox,表示其中的小插件是水平布局的:
// create a new vbox and add the subcontrols
let vbox = new VBox()
vbox.Add(label)
vbox.Add(button)
清单 8-9 是完整的示例,代码的运行结果产生图像如图 8-10 所示。
open Gtk
let main() =
// initalize the GTK environment
Application.Init()
// create the window
let win = new Window("GTK# and F# Application")
// set the windows size
win.Resize(400, 400)
// create a label
let label = new Label()
// create a button and subscribe to
// its clicked event
let button = new Button(Label = "Press Me!")
button.Clicked.Add(fun _ ->
label.Text <- "HelloWorld.")
// create a new vbox and add the sub controls
let vbox = new VBox()
vbox.Add(label)
vbox.Add(button)
// add the vbox to the window
win.Add(vbox)
// show the window
win.ShowAll()
// close the event loop when the window closes
win.Destroyed.Add(fun _ -> Application.Quit())
// start the event loop
Application.Run()
do main()
图 8-10 运行在 Linux 下的 GTK 应用程序