tags:

views:

252

answers:

1

Using Windows Forms or WPF I can open a dialog window by calling ShowDialog. How can I do that using Gtk#?

I tried just making the Window modal, but although it prevents the user from interacting with the calling window it does not wait for the user to close the dialog before running the code after ShowAll().

+3  A: 

Instead of using a Gtk.Window, use Gtk.Dialog, then call dialog.Run (). This returns an integer value corresponding to the ID of the button the user used to close the dialog.

e.g.

Dialog dialog = null;
ResponseType response = ResponseType.None;

try {
    dialog = new Dialog (
        "Dialog Title",
        parentWindow,
        DialogFlags.DestroyWithParent | DialogFlags.Modal,
        "Overwrite file", ResponseType.Yes,
       "Cancel", ResponseType.No
    );
    dialog.VBox.Add (new Label ("Dialog contents"));
    dialog.ShowAll ();

    response = (ResponseType) dialog.Run ();
} finally {
    if (dialog != null)
        dialog.Destroy ();
}

if (response == ResponseType.Yes)
    OverwriteFile ();

Note that Dispose()ing a widget in GTK# doesn't Destroy() it in GTK# -- a historical design accident, preserved for backwards-compatibility. However, if you use a custom dialog subclass you can override Dispose to also Destroy the dialog. If you also add the child widgets and the ShowAll() call in the constructor, you can write nicer code like this:

ResponseType response = ResponseType.None;
using (var dlg = new YesNoDialog ("Title", "Question", "Yes Button", "No Button"))
    response = (ResponseType) dialog.Run ();

if (response == ResponseType.Yes)
        OverwriteFile ();

Of course, you could take it a step further and write an equivalent of ShowDialog.

mhutch