WPF Application same size at every system scale (scale independent)

时光总嘲笑我的痴心妄想 提交于 2019-12-05 09:53:29

Finally found an answer. First get system DPI scale using one of the options below:

  • Read from registry AppliedDPI dword located in Computer\HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics. Then divide it by 96.
  • Or use this snippet:

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

    that returns a value between 1.0 to 2.5

Then create a config file that holds application settings and set dpiFactor as default scale. If user preferred a custom scale, call this function on window startup:

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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!