System.Drawing.Graphics.DpiX always return 96

前端 未结 3 808
隐瞒了意图╮
隐瞒了意图╮ 2021-01-24 07:37

I have vb.net winform app that has AutoScaleMode = dpi AutoScale = false AutoSize = true

I\'ve signed off after changing DPI setting. I also tried restarting the machine

3条回答
  •  感动是毒
    2021-01-24 08:06

    Unfortunately, the way windows handles DPI scaling is all over the place:

    Using g As Graphics = form.CreateGraphics()
    Dim dpiX As Single = g.DpiX
    

    This code will only work if user has "Use Windows XP Style DPI Scaling" selected when setting custom DPI. Don't know if that option is even available in the new versions of Windows (8.x and 10) or if they've taken it out.

    Your best bet would be to just read the registry:

        Dim regUseDpiScaling As Integer
        Try 'Use Try / Catch since the reg value may not exist if user using 96 DPI.
            regUseDpiScaling = CInt(My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM", "UseDpiScaling", Nothing)) ' if this returns 1, it means users is using modern DPI scaling.
        Catch ex As Exception
            regUseDpiScaling = 0 ' 0 means no DPI scaling or XP DPI scaling
        End Try
        If Not (regUseDpiScaling = 0) Then
            boolUsesModernDPIScaling = True 'Means you haven't clicked "Use Windows XP Style DPI Scaling" while setting DPI in your system.
        Else
            boolUsesModernDPIScaling = False
            MsgBox("2")
        End If
    
        Dim regAppliedDPI As Integer
        Try
            regAppliedDPI = CInt(My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics", "AppliedDPI", Nothing))
        Catch ex As Exception
            regAppliedDPI = 96
        End Try
        DPIratioX = regAppliedDPI / 96 
        DPIratioY = regAppliedDPI / 96
    

    I found that having XP DPI scaling can result in different behavior, so it's good to have the program detect if it's being used.

提交回复
热议问题