为了账号安全,请及时绑定邮箱和手机立即绑定

Xamarin.Forms.Platform.Gtk 处理主窗口关闭按钮单击(应用程序退出)

Xamarin.Forms.Platform.Gtk 处理主窗口关闭按钮单击(应用程序退出)

C#
紫衣仙女 2023-09-16 20:08:28
我正在使用 GTK 平台实现的 Xamarin.Forms 应用程序。我想做的是在用户关闭主窗口后显示确认警报。警报应询问用户是否要继续并退出应用程序。这在 WPF 平台上相当容易,但在 GTK 平台上却很困难。订阅DeleteEvent没有帮助。我的代码是这样的:[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}预计单击应用程序窗口的“关闭”按钮或 Alt + F4 将触发DeleteEvent并调用Window_DeleteEvent逻辑,但事件不会触发并且应用程序关闭。更新共享项目:Net Standard 2.0 Xamarin.Forms 版本 4.1.0.618606GTK项目:Net Framework 4.8 Xamarin.Forms版本4.1.0.618606 Xamarin.Forms.Platform.GTK版本3.6.0.344457
查看完整描述

1 回答

?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

事实证明,解决方案非常简单。我所要做的就是继承


Xamarin.Forms.Platform.GTK.FormsWindow 

并覆盖


protected override bool OnDeleteEvent(Event evnt)

像这样


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);

    }

  }

当然,为了使这项工作正常进行,我们的主窗口应该具有新类的类型。


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();

}

}


查看完整回答
反对 回复 2023-09-16
  • 1 回答
  • 0 关注
  • 46 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信