c# - WPF 应用程序在每个系统规模上都具有相同的大小(独立于规模)

标签 c# wpf scale dpi

有没有办法让 WPF 应用程序在每个系统规模上都获得相同的大小?

当我将 Windows 系统设置中的更改文本、应用和其他项目的大小125%(推荐)更改为100%时全高清屏幕,我的 WPF 应用程序变得太小了。为了实现独立的系统规模应用程序,我编写了一个这样的函数来将我的应用程序的缩放比例改回 125%:

private void ScaleTo125Percents()
{
    // Change scale of window content
    MainContainer.LayoutTransform = new ScaleTransform(1.25, 1.25, 0, 0);
    Width *= 1.25;
    Height *= 1.25;

    // Bring window center screen
    var screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
    var screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
    Top  = ( screenHeight - Height ) / 2;
    Left = ( screenWidth  - Width )  / 2;
}

但是调用这个函数是有条件的。第一个屏幕必须是全高清(有 API 可以检查这一点)并且系统比例必须是 100%(没有 .NET API 来获得系统比例)。

我能做什么?我是否正在采用标准方法使我的应用程序系统独立扩展?

我见过的与规模无关的应用程序示例:

  • Visual Studio 2017 安装程序
  • Telegram 桌面版

最佳答案

终于找到答案了。首先使用以下选项之一获取系统 DPI 比例:

  • 从位于 Computer\HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics 中的注册表 AppliedDPI 双字读取。然后除以 96。
  • 或者使用这个片段:

    double dpiFactor = System.Windows.PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice.M11;
    

    返回 1.0 到 2.5 之间的值

然后创建一个包含应用程序设置的配置文件,并将 dpiFactor 设置为默认比例。如果用户更喜欢自定义比例,请在窗口启动时调用此函数:

private void UserInterfaceCustomScale(double customScale)
{
    // Change scale of window content
    MainContainer.LayoutTransform = new ScaleTransform(customScale, customScale, 0, 0);
    Width *= customScale;
    Height *= customScale;

    // Bring window center screen
    var screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
    var screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
    Top  = ( screenHeight - Height ) / 2;
    Left = ( screenWidth  - Width )  / 2;
}

关于c# - WPF 应用程序在每个系统规模上都具有相同的大小(独立于规模),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44683626/

相关文章:

c# - 如何简化这个数组插入代码?

c# - 单元测试难题 : OleDbCommand

c# - TabItem/TabControl 中的 DataGridTextColumn 标题绑定(bind)问题

javascript - 缩放 Canvas 后如何在 Canvas 中以原始大小保存图像

C# 查看特定 .NET 类的源代码

c# - 当用户在 richtextbox 中输入大量数据时显示阅读更多选项

c# - 有没有办法用白色激活一个窗口?

c# - 图像上的 WPF 链式效果

ios - 从 URL 加载 UIImage 时在 UITableViewCell 中设置 UIImageView 大小?

jquery - 根据窗口高度缩放(CSS 变换)iframe