In my UWP app I'd like to set a minimum window size so that the window cannot be made smaller than that size.
Everywhere that I searched, it seems that using ApplicationView.PreferredLaunchViewSize
is the way to go but for some reason this is not working in my app.
I created a blank UWP app and updated the OnLaunched method as below:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
ApplicationView.PreferredLaunchViewSize = new Size(1200, 900);
ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(800, 600));
...
}
My App launches at the correct size of 1200 x 900 but I can shrink the window smaller than the limit of 800 x 600 which I've set for the app.
What is the right way to limit the window size so that it can't get smaller than a certain size ?
SetPreferredMinSize
is the correct API, but there are two important caveats:
First, remember that the APIs for CoreWindow operate in DIPS (Device Independent Pixel Space), not 'true pixels'. If you want to set a minimum of say 320 x 200 pixels, then you need to make sure to scale the values by the current DPI value.
Second, in UWP you really don't have hard control over presentation window size but can only express a preference. The reason you can't get 800 x 600 to work is that the 'maximum minimum' size is effectively 500 x 500 pixels. See MSDN.
In my Direct3D VS Game templates I use 320 x 200 as the minimum size:
C++/CX
auto minSize = Size(ConvertPixelsToDips(320), ConvertPixelsToDips(200));
view->SetPreferredMinSize(minSize);
C++/WinRT
auto minSize = Size(ConvertPixelsToDips(320), ConvertPixelsToDips(200));
view.SetPreferredMinSize(minSize);
Add to App.xaml code:
private readonly double minW = 800, minH = 600;
protected override void OnWindowCreated(WindowCreatedEventArgs args) {
SetWindowMinSize(new Size(args.Window.Bounds.Width, args.Window.Bounds.Height));
args.Window.CoreWindow.SizeChanged += CoreWindow_SizeChanged;
base.OnWindowCreated(args);
}
private void CoreWindow_SizeChanged(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.WindowSizeChangedEventArgs args) {
if (SetWindowMinSize(args.Size)) sender.ReleasePointerCapture();
}
private bool SetWindowMinSize(Size size) {
if (size.Width < minW || size.Height < minH) {
if (size.Width < minW) size.Width = minW;
if (size.Height < minH) size.Height = minH;
return ApplicationView.GetForCurrentView().TryResizeView(size);
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With