Intro to GTK with C#
Written By: James Williams
- 10 May 2006 -
Description: Why would anyone want to use GTK# when they can use Windows.Forms? It's cross-platform and more complete than the Mono implementation of Windows.Forms. GTK is also ingrained in the Linux community as the basis of one of the popular user interface systems, GNOME.
I've got Mono
No, not that mono. Our Mono is an open-source implementation of .NET backed by Novell that is fully compatible with the "classic" Microsoft version, save the GUI stuff. As stated before, Mono's implementation of Windows.Forms is incomplete but progressing towards completion. Even when it is completed, it would be somewhat of a moving target since Microsoft is likely to change things.
If you haven't already created the Glade GUI file, go ahead and do that now. Or download it. One of the great things about the C# Glade bindings is that they are tightly encapsulated. They hide so much of the internals that, in my opinion, they are more user-friendly than the Windows APIs. The resulting code is less cluttered and more readable.
On to the code
Because we are using GTK and Glade, it's understandable that we will need these namespaces.
using Gtk; using Glade;
In our Hello World constructor, we first call Application.Init() which as the name states, sets up the low level interfaces we need to run GTK. Next, we have
Glade.XML gxml = new Glade.XML(null, "gui.glade", "window1", null);
The first and last parameters are going to be null ninety-five percent of the time so I'm not going to discuss the situations in which they aren't. If you are really that curious, crack open the monodoc and have at it. Moving back to the code, gui.glade is the interface file and window1 is the widget to start with to build the interface. Because we can put multiple window definitions in the same file, it is important to specify it. Our next line
gxml.Autoconnect(this);
matches the stubs for the event handlers created in Glade with their actual implementations in our source code. Event handlers take the general form
public void event_handler_name(object sender, EventArgs e) { ... }
Autoconnect is another example of how Glade is hiding the nitty-gritty. If we had coded the GUI by hand, we would have attached each event handler individually to the corresponding event. Given a Window win, the following code would attach a window deletion handler to it.
win.DeleteEvent += new DeleteEventHandler(Window_Event); ... public void Window_Delete(object o, DeleteEventArgs args) { }
Sure, it would be a trivial change for our program but I like to be able to be lazy.