Application development using Gtk# in .Net

When I started my software development career, I got introduced to some cool tools for GUI application development in Linux. I was using Glade and the library was Gtk. Then later I become a MS fan and started working on ASP, VB and .Net. Yesterday I got a chance to download Mono and Monodevelop. And the Gtk for Windows and .Net called Gtk#. I explored in Mono Develop(I was downloaded MonoDevelop-2.2 beta 2) a little, but it was crashed for me two time. :( Then I started using Gtk# in VC# Express. And I created a simple Text File Viewer using C#, with Gtk# for UI. Most of the things in Gtk# is pretty different from .Net Windows Forms development. And I like the concept to in built support for predefined MenuItems, Icons etc. I think MS took the idea of commands in WPF from this.

I created a Windows Application Project and Added reference of the following libraries

atk-sharp.dll
gdk-sharp.dll
glade-sharp.dll
glib-sharp.dll
gtk-dotnet.dll
gtk-sharp.dll

And I deleted the Form1. And modified the Program.cs; the Program.cs

namespace HelloGtk
{
    using System;
    using Gtk;

    public class Program
    {
        private MainWindow mainWindow = null;

        public Program()
        {
            Application.Init();
            mainWindow = new MainWindow();
            Application.Run();
        }

        static void Main()
        {
            new Program();
            return;
        }
    }
}

And the added a class MainWindow.cs, and wrote the code

namespace HelloGtk
{
    using Gtk;
    using System.IO;

    public class MainWindow : Gtk.Window
    {
        private string title = "Text File Viewer";
        private VBox vbox;
        private MenuBar menubar;
        private Statusbar statusbar;
        private TextView textView;
        private ScrolledWindow scrolledWindow;
        private AccelGroup accelGroup;
        private Toolbar toolbar;
        public MainWindow()
            : base("Text File Viewer")
        {
            this.DefaultSize = new Gdk.Size(600, 500);
            this.DeleteEvent += new DeleteEventHandler(MainWindow_DeleteEvent);
            this.Build();
        }

        private void MainWindow_DeleteEvent(object o, DeleteEventArgs args)
        {
            Application.Quit();
            args.RetVal = true;
        }

        private void Build()
        {
            this.Title = this.title;
            this.vbox = new VBox(false, 0);
            this.CreateMenubar();
            this.vbox.PackStart(this.menubar, false, true, 0);
            this.toolbar = new Toolbar();
            this.CreateToolbar();
            this.vbox.PackStart(this.toolbar, false, true, 0);
            this.textView = new TextView();
            this.textView.Editable = false;
            this.textView.WrapMode = WrapMode.Word;
            this.scrolledWindow = new ScrolledWindow();
            this.scrolledWindow.SetPolicy(PolicyType.Automatic, PolicyType.Automatic);
            this.scrolledWindow.Add(this.textView);
            this.vbox.PackStart(this.scrolledWindow, true, true, 0);
            this.statusbar = new Statusbar();
            this.vbox.PackStart(this.statusbar, false, true, 0);
            this.Add(this.vbox);
            this.ShowAll();
        }
        private void CreateToolbar()
        {
            ToolButton OpenToolBarBtn = new ToolButton("gtk-open");
            OpenToolBarBtn.Clicked += this.openMenu_Activated;
            SeparatorToolItem Sep1 = new SeparatorToolItem();
            ToolButton CopyToolBarBtn = new ToolButton("gtk-copy");
            CopyToolBarBtn.Clicked += this.copyMenu_Activated;
            SeparatorToolItem Sep2 = new SeparatorToolItem();
            ToolButton AboutToolBarBtn = new ToolButton("gtk-about");
            AboutToolBarBtn.Clicked += this.aboutMenu_Activated;

            this.toolbar.Add(OpenToolBarBtn);
            this.toolbar.Add(Sep1);
            this.toolbar.Add(CopyToolBarBtn);
            this.toolbar.Add(Sep2);
            this.toolbar.Add(AboutToolBarBtn);
        }

        private void CreateMenubar()
        {
            this.accelGroup = new AccelGroup();
            this.menubar = new MenuBar();
            MenuItem fileMenu = new MenuItem("_File");
            MenuItem editMenu = new MenuItem("_Edit");
            MenuItem helpMenu = new MenuItem("_Help");
            helpMenu.RightJustified = true;

            Menu fileSubMenu = new Menu();
            TearoffMenuItem fileMenuTearOff = new TearoffMenuItem();
            ImageMenuItem openMenu = new ImageMenuItem("gtk-open", accelGroup);
            openMenu.Activated += new System.EventHandler(openMenu_Activated);
            SeparatorMenuItem fileMenuSep = new SeparatorMenuItem();
            ImageMenuItem exitMenu = new ImageMenuItem("gtk-quit", accelGroup);
            exitMenu.Activated += new System.EventHandler(exitMenu_Activated);
            fileSubMenu.Add(fileMenuTearOff);
            fileSubMenu.Add(openMenu);
            fileSubMenu.Add(fileMenuSep);
            fileSubMenu.Add(exitMenu);
            fileMenu.Submenu = fileSubMenu;

            Menu editSubMenu = new Menu();
            ImageMenuItem copyMenu = new ImageMenuItem("gtk-copy", accelGroup);
            copyMenu.Activated += new System.EventHandler(copyMenu_Activated);
            TearoffMenuItem editMenuTearOff = new TearoffMenuItem();
            editSubMenu.Add(editMenuTearOff);
            editSubMenu.Add(copyMenu);
            editMenu.Submenu = editSubMenu;

            Menu helpSubMenu = new Menu();
            ImageMenuItem aboutMenu = new ImageMenuItem("gtk-about", accelGroup);
            TearoffMenuItem helpMenuTearOff = new TearoffMenuItem();
            helpSubMenu.Add(helpMenuTearOff);
            helpSubMenu.Add(aboutMenu);
            aboutMenu.Activated += new System.EventHandler(aboutMenu_Activated);
            helpMenu.Submenu = helpSubMenu;

            this.menubar.Add(fileMenu);
            this.menubar.Add(editMenu);
            this.menubar.Add(helpMenu);
        }

        void aboutMenu_Activated(object sender, System.EventArgs e)
        {
            using (Dialog dialog = new MessageDialog(this,
                                  DialogFlags.Modal | DialogFlags.DestroyWithParent,
                                  MessageType.Info,
                                  ButtonsType.Ok,
                                  "Text File Viewer - A simple text file viewer using gtk#\nDeveloped by Anuraj\nPowered by dotnetthoughts.net\n\nUnder GNU GPL v2."))
            {
                dialog.Title = "About";
                dialog.Run();
                dialog.Hide();
            }
        }

        private void copyMenu_Activated(object sender, System.EventArgs e)
        {
            Clipboard clipboad = this.textView.GetClipboard(Gdk.Selection.Clipboard);
            this.textView.Buffer.CopyClipboard(clipboad);
        }

        void exitMenu_Activated(object sender, System.EventArgs e)
        {
            Application.Quit();
        }
        FileChooserDialog dlg;
        private void openMenu_Activated(object sender, System.EventArgs e)
        {
            dlg =
                new FileChooserDialog("Select Text File", this, FileChooserAction.Open, "");
            dlg.AddButton("Open File", ResponseType.Ok);
            dlg.AddButton("Cancel", ResponseType.Cancel);

            FileFilter filter = new FileFilter();
            filter.AddPattern("*.txt");
            filter.AddPattern("*.*");
            dlg.Filter = filter;

            dlg.TypeHint = Gdk.WindowTypeHint.Dialog;
            dlg.SelectMultiple = false;
            dlg.WindowPosition = WindowPosition.Center;
            dlg.Parent = this;
            dlg.Modal = true;
            dlg.KeepAbove = true;
            dlg.DestroyWithParent = true;
            dlg.State = StateType.Normal;

            dlg.Response += new ResponseHandler(dlg_Response);
            dlg.DeleteEvent += new DeleteEventHandler(dlg_DeleteEvent);

            dlg.Run();
            dlg.Destroy();

        }

        private void dlg_DeleteEvent(object o, DeleteEventArgs args)
        {
            dlg.Destroy();
        }

        private void dlg_Response(object o, ResponseArgs args)
        {
            if (args.ResponseId == ResponseType.Ok)
            {
                this.Title = string.Format("{0} - {1}", this.title, System.IO.Path.GetFileName(dlg.Filename));
                using (StreamReader reader = new StreamReader(dlg.Filename, true))
                {
                    this.textView.Buffer.Text = reader.ReadToEnd();
                }
            }
            dlg.Destroy();
        }
    }
}

And run the application. Here is the screenshot, Text File Viewer running on my machine.

Text File Viewer using GTK#

Text File Viewer using GTK#

This entry was posted in .Net, .Net 3.0 / 3.5, Visual Studio, Windows Forms and tagged , , , , , , . Bookmark the permalink.

2 Responses to Application development using Gtk# in .Net

  1. Brent says:

    Wow, thanks.

    After downloading the gtk sharp installers, I wandered around the intertubes for 45 minutes trying to figure out how to do a basic sample gtk app in visual studio and couldn’t find anything that was truly useful. All either used mono-develop, or didn’t work. I couldn’t even figure out what assemblies to reference.

    Turns out I was looking in the bin folder of the gtk-sharp folder rather than the lib folder. But at least your sample gave me the names of the dlls I was looking for. And, a code sample that actually works…. amazing.

    I’m very glad to be able to use VS to build Linux capable apps. (Despite all of the noise from fanboys out there who want to chime in with reasons that this isn’t necessary rather than offering useful help).

    I will say, that I used a console app instead of the windows forms app project template, and then went in and changed the output type to “Windows Application” doing this created a project with significantly fewer references that might add GUI related stuff to my auto-complete box that I didnt want in there.

    Thanks for an excelent post.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>