I'm developing a WinUI 3 desktop application using Template Studio, and I'm encountering difficulties with monitoring display changes such as orientation and DPI. The application uses custom windows derived from WindowEx
, and I need to attach event handlers for display changes.
Here's the simplified code illustrating my approach:
using Microsoft.UI.Dispatching;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
namespace EasyDisplay;
public sealed partial class MainWindow : WindowEx
{
public MainWindow()
{
InitializeComponent();
Content = null;
Title = "AppDisplayName".GetLocalized();
this.Activated += WindowEx_Activated;
}
private void DisplayInformation_OrientationChanged(DisplayInformation sender, object args)
{
// Intended handling of orientation changes
}
private void WindowEx_Activated(object sender, Microsoft.UI.Xaml.WindowActivatedEventArgs args)
{
this.Activated -= WindowEx_Activated; // To avoid multiple subscriptions
App.MainWindow.DispatcherQueue.TryEnqueue(() =>
{
var displayInformation = DisplayInformation.GetForCurrentView();
displayInformation.OrientationChanged += DisplayInformation_OrientationChanged;
});
}
}
Whenever I attempt to access DisplayInformation.GetForCurrentView(), I encounter the following COMException error, regardless of whether the code is placed in MainWindow or within a page:
Exception thrown: 'System.Runtime.InteropServices.COMException' in WinRT.Runtime.dll
WinRT information: Windows.Graphics.Display: GetForCurrentView must be called on a thread that is associated with a CoreWindow.
Element not found.
I've tried various approaches to ensure I'm on the UI thread and to defer the event subscription until the window is fully activated, but the error persists.
What is the correct way to detect display changes such as orientation and DPI in WinUI 3 using WindowEx? Is there a specific point in the application lifecycle or a particular technique to successfully attach these event handlers?
DisplayInformation.GetForCurrentView()
is no longer supported in WinUI 3.
Currently there is no OrientationChanged
event in WinUI3, you should wait for version 1.5. If you use wasdk v1.5-exp2 you can access this new api.
Mybe you can use SizeChanged event until exp2 api comes to v.1.5 stable.
As you can see in omd link, OrientationChanged
added in Microsoft.Graphics.Display.DisplayInformation
https://omds.xaml.dev/WinAppSDKv1.4_v1.5e2.html