Home > Back-end >  How to move and minimize Maui windows application programmatically
How to move and minimize Maui windows application programmatically

Time:09-04

I have a maui app with blazor and I'm creating a custom titlebar.

I about to close the maui app, using on blazor Application.Current.Quit();

Now how can i minimize and move maui app

My code blazor

private void MoveWindow()
{
    
}

private void MinimizeWindow()
{
        
}


private void CloseWindow() {
    Application.Current.Quit();
}

CodePudding user response:

Maui already has a function to minimize the application.

Use the following in your blazor:

private void MinimizeWindow()
{
#if WINDOWS
    var Window = App.Current.Windows.First();
    var nativeWindow = Window.Handler.PlatformView;
    IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(nativeWindow);
    WindowId WindowId = Win32Interop.GetWindowIdFromWindow(windowHandle);
    AppWindow appWindow = AppWindow.GetFromWindowId(WindowId);

    var p = appWindow.Presenter as OverlappedPresenter;

    p.Minimize();
#endif
}

CodePudding user response:

You need to call native code for that. Add a reference to PInvoke.User32 package:

<PackageReference Include="PInvoke.User32" Version="0.7.104" Condition="$([MSBuild]::IsOSPlatform('windows'))"/>

Minimize

As an example upon a button click we minimize the window:

void MinimizeWindow(object sender, EventArgs e)
{
#if WINDOWS
            var mauiWindow = App.Current.Windows.First();
            var nativeWindow = mauiWindow.Handler.PlatformView;
            IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(nativeWindow);

            PInvoke.User32.ShowWindow(windowHandle, PInvoke.User32.WindowShowStyle.SW_MINIMIZE);
#endif
}

Move

void MoveWindow(object sender, EventArgs e)
{
#if WINDOWS
            var mauiWindow = App.Current.Windows.First();
            var nativeWindow = mauiWindow.Handler.PlatformView;
            IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(nativeWindow);
            PInvoke.RECT rect;

            PInvoke.User32.GetWindowRect(windowHandle, out rect);
            (var width, var height) = GetWinSize(rect);

            PInvoke.User32.MoveWindow(windowHandle, 50, 0, width, height, true);

#endif
}

(int width, int height) GetWinSize(PInvoke.RECT rect) =>
            (rect.right - rect.left, rect.bottom - rect.top);

It's possible to resize the window with MoveWindow(), but since the aim in the question is to move the window only, then we supply the values of the current window's width and height as parameters.

Ps: Unfortunately I didn't find a simpler solution to get the window dimensions.

  • Related