2009-12-14

GTK+ from F#

GTK+ is a graphical user interface toolkit that can be used to build applications for Windows, Mac OS X, or Linux/Unix.  Gtk# provides .NET language bindings for GTK+.  I simply downloaded Mono 2.4.3 and installed it on my Windows 7 PC.  You can also download Gtk# for Windows without Mono at the same link.  After installing Mono, I added C:\Program Files (x86)\Mono-2.4.3\bin to the PATH system environment variable.  This is required so that the .NET runtime will find the GTK+ dynamic-link libraries.  I created and added the Gtk# libraries (gtk-sharp.dll, atk-sharp.dll, gdk-sharp.dll, glib-sharp.dll) found in C:\Program Files (x86)\Mono-2.4.3\lib\mono\gtk-sharp-2.0 to a new F# project.

The GtkWindowExample.fs simply creates a window with a title and it shuts down correctly when you click on the close window button.  It is the Hello World of Gtk# and can be found in C# with more comments here and here.  I was able to build, run and debug it from within Visual Studio 2010 Beta 2.  I was also able to run it from Mono in Windows and on my Mac.  The GtkWindowExample.exe works in all three environments.

Some troubleshooting notes:

  • The distributed GTK+ is currently 32-bit, so the platform target needs to be x86, not x64 or Any CPU.  Project Properties > Build > Platform target.
  • When running from Mono, to avoid the error message of WARNING: The runtime version supported by this application is unavailable. Using default runtime: v1.1.4322, you must ensure:
    • The F# project must reference mscorlib, which it does by default.
    • The Target Framework needs to be ".NET Framework 2.0" or ".NET Framework 3.5".  The default was “.NET Framework 4 Client Profile, which Mono doesn’t support yet.
  • The Gtk# libraries are already in Mono’s GAC and they are OS dependant.

The code can be browsed here or checked out:

svn checkout http://ctaggart.googlecode.com/svn/tags/blog-2009/2009-12-14/GtkWindowExample/

It looks like people have been using Gtk# with F# for more than 3 years now, so I’m not the first, but hopefully some find this post helpful.