Search code examples
c#.netuser-interfacescreenavaloniaui

Set Window Startup Location to bottom right


I'm completely new in developing Programs in C# and AvaloniaUI. I want to code a Chat App that should start in a small Format at the bottom right but there's no "WindowStartupLocation" predefined just for "CenterOwner" and "CenterScreen". I've also took a look into the AvaloniaUI Documentation but doesn't really fount something useful.


Solution

  • Remember that Avalonia is cross platform and iOS/Android compatible. The latter of which do not support the concept of Windows. Due to this, you have to access the ApplicationLifetime when dealing with purely desktop concepts, unless you do it in the MainWindow itself. I will demonstrate both ways.

    The working area gives you the screen size minus OS components (i.e. the start menu). Then you have to convert the window size to match the PixelSize format and then do the usual calculations for position.

    In the second example I did this in the MainWindow OnLoaded event. Do not ever attempt the first example in the MainWindow constructor as it will not exist at the time you are trying to reference it.

    Externally:

    Window window = GetSomeWindowSomehow();
    if (Application.Current?.ApplicationLifetime is
        IClassicDesktopStyleApplicationLifetime desktop)
    {
      Avalonia.Platform.Screen screen = desktop.MainWindow.Screens.Primary;
      PixelSize screenSize = screen.WorkingArea.Size;
      PixelSize windowSize = PixelSize.FromSize(window.ClientSize, screen.Scaling);
    
      window.Position = new PixelPoint(
        screenSize.Width - windowSize.Width,
        screenSize.Height - windowSize.Height);
    }
    

    In the MainWindow:

    private void OnLoaded(object? sender, EventArgs args)
    {
      PixelSize screenSize = Screens.Primary.WorkingArea.Size;
      PixelSize windowSize = PixelSize.FromSize(ClientSize, Screens.Primary.Scaling);
    
      Position = new PixelPoint(
        screenSize.Width - windowSize.Width,
        screenSize.Height - windowSize.Height);
    }