Search code examples
c#macosxamarin.formswindowpositioning

Remember window position with Xamarin Forms Mac OS


I understand that XCode supports AutoSave for remembering window position. I see it freely documented.

What about Xamarin Forms 5, when the platform is macOS?

This is some of my code, if it helps:

public class AppDelegate : FormsApplicationDelegate
{
    NSWindow window;
    public AppDelegate()
    {
        var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled;

        var rect = new CoreGraphics.CGRect(200, 1000, 1024, 768);
        window = new NSWindow(rect, style, NSBackingStore.Buffered, false)
        {
            Title = "Elderly and Infirm Rota",
            TitleVisibility = NSWindowTitleVisibility.Visible
        };

        InstallApplicationFiles();
    }

Update

In the comments I also referred to limiting the size of the window. I have now worked out that bit (NSWindow.MinSize):

NSWindow window;
public AppDelegate()
{
    var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled;

    var rect = new CoreGraphics.CGRect(200, 1000, 1024, 768);
    window = new NSWindow(rect, style, NSBackingStore.Buffered, false)
    {
        Title = "Elderly and Infirm Rota",
        TitleVisibility = NSWindowTitleVisibility.Visible,
        MinSize = rect.Size
    };

    InstallApplicationFiles();
}

Now I have to address the window size / position and remembering it.


Solution

  • Turns out it was not too hard. Visual Studio for Mac is missing some settings (I think) that are described for Xcode. See: frameAutoSaveName

    The answers provided here were also useful. Part of the problem for me was having the right terms to search for an answer and in this case NSWindow was important.

    In my macOS AppDeletegate constructor I now do this:

    public AppDelegate()
    {
        var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled;
    
        var rect = new CoreGraphics.CGRect(200, 1000, 1024, 768);
        window = new NSWindow(rect, style, NSBackingStore.Buffered, false)
        {
            Title = NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleDisplayName").ToString(),
            TitleVisibility = NSWindowTitleVisibility.Visible,
            MinSize = rect.Size,
            FrameAutosaveName = "xxxxx"
        };
    
        InstallApplicationFiles();
    }
    

    Notice the additional setting of the FrameAutosaveName property:

    FrameAutosaveName = "xxxxx"
    

    Now the window position is remembers when I close the application.


    Please let me know if there was a way to set this directly in Visual Studio for Mac GUI.