LoginSignup
3
4

More than 5 years have passed since last update.

Xamarin.Macでウィンドウを閉じる前に確認する

Last updated at Posted at 2014-08-19

Problem

たとえばAppDelegate.cs で以下のように記述すると,最後のウィンドウが閉じた瞬間にアプリケーションを落とすことができます。

AppDelegate.cs
public override bool ApplicationShouldTerminateAfterLastWindowClosed(NSApplication sender)
{
    return true;
}

ここに確認をはさみたいとき。
上記のようにApplicationShouldTerminateをオーバーライドしないときももちろん有効。

Solution

NSWindowDelegateを継承したクラスを作成し,これをWindowのDelegateに設定します。MainWindowControllerのInitializeあたりで設定すればよいでしょう。

作成したデリゲートでWindowShouldCloseをオーバーライドして,確認ダイアログをはさみます。falseを返せば閉じられるのをキャンセルできます。

MainWindowDelegate.cs
using System;
using MonoMac.AppKit;

namespace Qiita.Sample.XamMac.Notify
{
    public class MainWindowDelegate : NSWindowDelegate
    {
        public MainWindowDelegate()
        {
        }

        public override bool WindowShouldClose(MonoMac.Foundation.NSObject sender)
        {
            using (var alert = new NSAlert())
            {
                alert.AlertStyle = NSAlertStyle.Informational;
                alert.MessageText = "ほんと?";
                alert.InformativeText = "ほんとに閉じていいですか?";
                alert.AddButton("はい");
                alert.AddButton("いいえ");
                var ret = alert.RunSheetModal(sender as NSWindow);
                return (ret == (int)NSAlertButtonReturn.First);
            }
        }
    }
}

senderがnullになっても,普通のダイアログとして表示されるだけなので大丈夫です(そもそもならないはず)。

Conclusion

デリゲート地獄。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4