Search code examples
macoseventsmonoexitmonomac

Handle a MonoMac Exit/Window Close Event


Similar to this question I posted earlier: Handle a WPF Exit Event

I found a solution in Objective C, but I'm not familiar with how to port this with Mono.

EDIT

I found that I could use the following override to do what I wanted to:

NSApplicationTerminateReply ApplicationShouldTerminate (NSApplication sender)

However, there is a problem now if I close my MainWindow since that is actually where I want to start calling application exit. I already have an override for ApplicationShouldTerminateAfterLastWindowClosed that returns true, so the terminate override is being called correctly. But when I'm returning Cancel, the app is running, sans window. Is there a way to intercept the window closing event?


Solution

  • This is what I ended up doing. I created a new class called MainWindowDelegate:

    public class MainWindowDelegate : MonoMac.AppKit.NSWindowDelegate
    {
        public override WindowShouldClose (MonoMac.Foundation.NSObject sender)
        {
            return false;
        }
    }
    

    Then, in my MainWindowController class:

    public class MainWindowController
    {
        private MainWindowDelegate _delegate;
    
        // Shared initialization code
        void Initialize()
        {
            _delegate = new MainWindowDelegate();
        }
    
        public override void WindowDidLoad()
        {
            Window.Delegate = _delegate;
        }
    }