0
votes

I'm having Xamarin.Forms application with GTK platform implementation. What I'm trying to do is to show confirmation alert once user closes main window. The alert should ask user if he wants to proceed and exit application. That was pretty easy on WPF platform, but there were difficulty with GTK platform.

Subscribing to DeleteEvent didn't help.

My code is something like this:

[STAThread]
public static void Main(string[] args)
{
    Gtk.Application.Init();
    Forms.Init();
    var app = new App();
    var window = new FormsWindow();
    window.LoadApplication(app);
    window.SetApplicationTitle("Nts");
    window.Show();

    window.DeleteEvent += Window_DeleteEvent; //this is not fired

    Gtk.Application.Run();
}

private static void Window_DeleteEvent(object o, Gtk.DeleteEventArgs args)
{
    //show alert
}

Expected that on clicking "Close" button or Alt + F4 of application window will fire the DeleteEvent and call Window_DeleteEvent logic but event is not fired and application closes.

Updated

Shared project: Net Standard 2.0 Xamarin.Forms version 4.1.0.618606

GTK project: Net Framework 4.8 Xamarin.Forms version 4.1.0.618606 Xamarin.Forms.Platform.GTK version 3.6.0.344457

1
Does it work if you subscribe before showing it?BugFinder
@BugFinder unfortunately no, behavior is the sameAlexander Yashyn
what version of XF are you using?knocte
@knocte , I've added versions to questionAlexander Yashyn

1 Answers

0
votes

It turned out that solution is pretty simple. All I had to do is to inherit from

Xamarin.Forms.Platform.GTK.FormsWindow 

and override

protected override bool OnDeleteEvent(Event evnt)

like this

public class MyFormsWindow: FormsWindow
{
  protected override bool OnDeleteEvent(Event evnt)
  {
    var messageDialog = new MessageDialog(Program.MainWindow, DialogFlags.Modal, 
    MessageType.Question, ButtonsType.YesNo,
      "Do you want to exit?", String.Empty)
    {
      Title = "Confirmation",
    };
    int result = messageDialog.Run();

    //the magic numbers stand for "Close" and "No" results
    if (result == -4
      || result == -9
    {
      messageDialog.Destroy();
      return true; // true means not to handle the Delete event by further handlers, as result do not close application
    }
    else
    {
      messageDialog.Destroy();
      return base.OnDeleteEvent(evnt);
    }
  }

And of course to make this work our Main window should have type of new class.

public class Program
{
public static MyFormsWindow MainWindow { get; private set; }

[STAThread]
public static void Main(string[] args)
{
    Gtk.Application.Init();
    Forms.Init();

    var app = new App();
    var window = new MyFormsWindow();
    window.LoadApplication(app);
    window.SetApplicationTitle("MyApp");
    window.Show();

    MainWindow = window;

    Gtk.Application.Run();
}
}