windowsblazormauimaui-blazor

Blazor Hybrid window move event?


I've been trying to find how to register the move event of any of the windows types in a blazor hybrid app.

All of these have a SizeChanged event or similarly named, but none of them something like Position/LocationChanged event / OnMove/d, etc.

Microsoft.Maui.Controls.Window
Microsoft.UI.Windowing.AppWindow
Microsoft.UI.Windowing.OverlappedPresenter

#if WINDOWS So, is there a way to detect the window movement? Even if we need to stoop low, pun intended. #endif

WebView2 should support this, as the appWindow of Tauri does have an onMoved event. Or I suppose it comes from WebView2.

This has been corrected; otherwise it would have been super useful: https://github.com/dotnet/maui/issues/17991


Solution

  • You could use the PropertyChanged event.

    public partial class App : Application
    {
      public App()
      {
        InitializeComponent();
      }
    
      protected override Window CreateWindow(IActivationState? activationState)
      {
        var window = new Window(new MainPage()) { Title = "MauiApp7" };
    
        // Add a PropertyChanged event handler
        window.PropertyChanged += Window_PropertyChanged;
    
        return window;
      }
    
      private void Window_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
      {
        // Check if the X or Y property changed
        if (e.PropertyName == nameof(Window.X) || e.PropertyName == nameof(Window.Y))
        {
          var window = (Window)sender!;
          // Execute your code here when X or Y changes
          window.Title = $"Window X position changed to: {window.X}, {window.Y}";
        }
      }
    }