在Win10 UWP应用程序中获取屏幕分辨率
由于UWP App在普通桌面系统上以窗口模式运行,因此获取屏幕分辨率的“旧”方式将不再适用。
Window.Current.Bounds
旧分辨率如图所示。
有没有其他方法来获得(主)显示的分辨率?
为了进一步改进其他答案,下面的代码也会考虑缩放因子,例如我的Windows显示器的200%(正确返回3200×1800)和Lumia 930的300%(1920×1080)。
var bounds = ApplicationView.GetForCurrentView().VisibleBounds; var scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel; var size = new Size(bounds.Width*scaleFactor, bounds.Height*scaleFactor);
如其他答案中所述,这只会在更改根帧大小之前在桌面上返回正确的大小。
随时随地调用此方法(在移动/桌面应用程序中测试):
public static Size GetCurrentDisplaySize() { var displayInformation = DisplayInformation.GetForCurrentView(); TypeInfo t = typeof(DisplayInformation).GetTypeInfo(); var props = t.DeclaredProperties.Where(x => x.Name.StartsWith("Screen") && x.Name.EndsWith("InRawPixels")).ToArray(); var w = props.Where(x => x.Name.Contains("Width")).First().GetValue(displayInformation); var h = props.Where(x => x.Name.Contains("Height")).First().GetValue(displayInformation); var size = new Size(System.Convert.ToDouble(w), System.Convert.ToDouble(h)); switch (displayInformation.CurrentOrientation) { case DisplayOrientations.Landscape: case DisplayOrientations.LandscapeFlipped: size = new Size(Math.Max(size.Width, size.Height), Math.Min(size.Width, size.Height)); break; case DisplayOrientations.Portrait: case DisplayOrientations.PortraitFlipped: size = new Size(Math.Min(size.Width, size.Height), Math.Max(size.Width, size.Height)); break; } return size; }
好吧, Juan Pablo Garcia Coello的回答引导我找到解决方案 – 谢谢!
您可以使用
var bounds = ApplicationView.GetForCurrentView().VisibleBounds;
但是你必须在我的情况下立即显示窗口之前调用它
Window.Current.Activate();
是个好地方。 此时,您将获得应用程序将出现的窗口范围。
非常感谢帮助我解决它:)
关心亚历克斯
我找到的唯一方法是在Page的构造函数中:
public MainPage() { this.InitializeComponent(); var test = ApplicationView.GetForCurrentView().VisibleBounds; }
我没有在Windows 10 Mobile中测试,当新版本出现时我会测试它。
更简单的方法:
var displayInformation = DisplayInformation.GetForCurrentView(); var screenSize = new Size(displayInformation.ScreenWidthInRawPixels, displayInformation.ScreenHeightInRawPixels);
这不取决于当前视图大小。 它随时会返回真正的屏幕分辨率。
使用此方法获取屏幕大小:
public static Size GetScreenResolutionInfo() { var applicationView = ApplicationView.GetForCurrentView(); var displayInformation = DisplayInformation.GetForCurrentView(); var bounds = applicationView.VisibleBounds; var scale = displayInformation.RawPixelsPerViewPixel; var size = new Size(bounds.Width * scale, bounds.Height * scale); return size; }
你应该在Window.Current.Activate()之后从App.xaml.cs调用这个方法; 在OnLaunched方法中。
这是示例代码,您可以下载完整的项目。
只需为主Grid或Page设置一个名称,并为所需的元素调用其宽度或高度:
Element.Height = PagePane.Height; Element.width = PagePane.Width;
这是你可以使用的最简单的方法!