亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 113 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號