Skip to content

Commit 08a2477

Browse files
Add methods to get proper bounds for WinAppSDK
1 parent 7f68049 commit 08a2477

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

common/CommunityToolkit.Labs.Tests.Shared/App.xaml.cs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
using Windows.UI.Xaml.Navigation;
1818
#else
1919
using Microsoft.UI.Dispatching;
20+
using Microsoft.UI.Windowing;
2021
using Microsoft.UI.Xaml;
2122
using Microsoft.UI.Xaml.Controls;
2223
using Microsoft.UI.Xaml.Controls.Primitives;
@@ -38,11 +39,33 @@ public sealed partial class App : Application
3839
// Using static will not work.
3940
#if WINAPPSDK
4041
private static Microsoft.UI.Xaml.Window currentWindow = Microsoft.UI.Xaml.Window.Current;
42+
43+
private static AppWindow GetAppWindow(Microsoft.UI.Xaml.Window window)
44+
{
45+
// From: https://docs.microsoft.com/en-us/windows/apps/windows-app-sdk/windowing/windowing-overview#code-example
46+
// Retrieve the window handle (HWND) of the current (XAML) WinUI 3 window.
47+
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
48+
49+
// Retrieve the WindowId that corresponds to hWnd.
50+
var windowId = Win32Interop.GetWindowIdFromWindow(hWnd);
51+
52+
// Lastly, retrieve the AppWindow for the current (XAML) WinUI 3 window.
53+
return AppWindow.GetFromWindowId(windowId);
54+
}
55+
56+
public static Rect Bounds { get
57+
{
58+
var appWindow = GetAppWindow(currentWindow);
59+
var position = appWindow.Position;
60+
var size = appWindow.Size;
61+
return new Rect(position.X, position.Y, size.Width, size.Height);
62+
}
63+
}
4164
#else
4265
private static Windows.UI.Xaml.Window currentWindow = Windows.UI.Xaml.Window.Current;
43-
#endif
4466

4567
public static Rect Bounds => currentWindow.Bounds;
68+
#endif
4669

4770
// Holder for test content to abstract Window.Current.Content
4871
public static FrameworkElement? ContentRoot

0 commit comments

Comments
 (0)