Defining a minimum (or maximum) window size in UWP
In UWP the UI is meant to be responsive, so the user can set any window size they want. But for certain apps that can be a problem as they need a minimum size to work. So what to do?
There is a way to set the preferred size of your window on startup like so:
ApplicationView.PreferredLaunchViewSize = new Size(1280, 720); ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
But that does not prevent the user from grabbing the edge of the window and resize it. You can set a minimum window size like so:
ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(200, 100));
But guess what? The smallest allowed minimum size is 192 x 48 effective pixels. The largest allowed minimum size is 500 x 500 effective pixels. Anything outside of these bounds will be set to the nearest one.
You can however attach yourself to the SizeChanged event and then forcefully resize the window if the user goes outside of your own bounds. This will lead to a LOT of flickering as the user drags.
So we wait until the user is finished with dragging the window border and then resize. The only issue is that there is no event for when the user is finished. Oh well, let's use a timer hack instead.
// Define masterTimer with "static ThreadPoolTimer windowResizeTimer;" // somewhere with global scope. // Also add "Window.Current.CoreWindow.SizeChanged += UpdateUI;" on page creation. public void UpdateUI(CoreWindow sender, WindowSizeChangedEventArgs e) { // Check if the timer is already running. // If so, then cancel it. It will be re-created below. if (windowResizeTimer != null) windowResizeTimer.Cancel(); // Set the timeout to 1 second. TimeSpan timeout = new TimeSpan(0, 0, 0, 1); // Create a new timer. After the timeout, the resize code will be executed. windowResizeTimer = ThreadPoolTimer.CreateTimer(async (ThreadPoolTimer timer) => { // Get the new window width and height. double newHeight = e.Size.Height; double newWidth = e.Size.Width; bool minSizeReached = false; // Check if the window is too narrow. if (newWidth < YourMinimumWidth) { newWidth = YourMinimumWidth; minSizeReached = true; } // Check if the window is too small. if (newHeight < YourMinimumHeight) { newHeight = YourMinimumHeight; minSizeReached = true; } // If anything was wrong, resize the window. if (minSizeReached) { await theDispatcherForTheCurrentView.RunAsync( CoreDispatcherPriority.Normal, () => { ApplicationView.GetForCurrentView().TryResizeView(new Size(newWidth, newHeight)); }); } }, timeout); }
And there you go. The user resizes the window, it adjusts itself nicely after they are done. And boy, you should really just do it responsively.









