2

I've recently started working on Gtk+ 3.x with the Vala programming language. I used to use C# and visual studio for much the same task, but have since moved to Linux.

How do I go about asking a simple Ok / Cancel question in a dialog? In C# it was really easy with MessageBox.Show(). However, Gtk seems to be annoyingly complex, and each Google search I have made has landed me with technical gibberish about Dialogs and event handlers.

Is there just a simple function, so I could do something like:

bool result = MessageBox.AskQuestion("Do you want to save?");

Thanks,

Barry Smith

Barry Smith
  • 281
  • 1
  • 4
  • 16

2 Answers2

4

Actually, found it out via trial and error...

public bool show_question(string message, Gtk.Window window, MessageType mt)
{
    Gtk.MessageDialog m = new Gtk.MessageDialog(window, DialogFlags.MODAL, mt, ButtonsType.OK_CANCEL, message);
    Gtk.ResponseType result = (ResponseType)m.run ();
    m.close ();
    if (result == Gtk.ResponseType.OK)
    {
        return true;
    }
    else
    {
        return false;
    }
}
Barry Smith
  • 281
  • 1
  • 4
  • 16
3

A slightly improved version:

public bool show_question(string primary_markup,
                          string? secondary_markup = null,
                          Gtk.Window? parent = null,
                          Gtk.MessageType message_type = Gtk.MessageType.QUESTION)
{
    var m = new Gtk.MessageDialog.with_markup(parent,
                                              Gtk.DialogFlags.MODAL,
                                              message_type,
                                              Gtk.ButtonsType.OK_CANCEL,
                                              primary_markup);
    m.format_secondary_markup(secondary_markup);
    var result = (Gtk.ResponseType) m.run();
    m.destroy();
    return (result == Gtk.ResponseType.OK);
}

This new version takes advantage of Vala's default parameters, so in the simplest case you can just call show_question("Is this OK?");. Furthermore, you can also now use Pango Markup to generate much nicer looking dialogs, for example:

show_question("<b><big>Overwrite File?</big></b>",
              "<small>The file <i>\"%s\"</i> will be overwritten if you proceed</small>".printf(my_filename),
              parent_window,
              Gtk.MessageType.WARNING);

It's worth noting however that in GTK, using plain "OK/CANCEL" responses like this is generally frowned upon. Instead the recommendation is to use button labels that contain verbs pertaining to the action in question; so in the above example, "Cancel" and "Overwrite" would be much better options (defaulting to Cancel, of course). This takes a little but more work for the programmer, but provides a better user experience.

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82