Marking Your Python Program as High DPI Aware Seamlessly Windows

梦想的初衷 提交于 2019-12-11 03:21:24

问题


I just wanted to share the best way I found to do this in case other people were having issues as I was. If your Python/Kivy program has graphic issues with Virtual DPI scaling try this code out. It'll mark the program as High DPI Aware for you or the end user without having to do anything. This works for Windows 10, not sure about 8 or 7. Was wondering if anyone else knows if this will work for 8 and 7. To test this out, add the code in, set DPI up, log out and back in of user so the registry marks the DPI change, and run your code from SHELL. Your program should be DPI aware now!

import winreg
from os import path as ospath
from os import execl as osexecl
from sys import executable as sysex
from sys import argv as sysargv

if __name__ == '__main__':
    reg = winreg.ConnectRegistry(None,winreg.HKEY_CURRENT_USER)
    key = winreg.OpenKey(reg, r"Control Panel\Desktop\WindowMetrics")
    print(winreg.QueryValueEx(key, 'AppliedDPI'))
    filefound=True
    if winreg.QueryValueEx(key, 'AppliedDPI')[0]!=96:
        key.Close()
        key = winreg.OpenKey(reg, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers", 0, winreg.KEY_ALL_ACCESS)

        ##If testing from SHELL also add these values into registry. This is not needed for complied EXEs. Make sure the path is correct or it won't work.

        winreg.SetValueEx(key, 'C:\python35\pythonw.exe', 0, winreg.REG_SZ, 'HIGHDPIAWARE')
        winreg.SetValueEx(key, 'C:\python35\python.exe', 0, winreg.REG_SZ, 'HIGHDPIAWARE')

        ##If Testing from SHELL change YOUREXE.exe to YOURPYFILE.py, otherwise it should be the name of your compiled EXE.

        exepath=str(ospath.abspath('YourEXE.exe'))
        try:
            winreg.QueryValueEx(key, exepath)
        except:
            print('FileNotFound')
            winreg.SetValueEx(key, exepath, 0, winreg.REG_SZ, 'HIGHDPIAWARE')
            print(winreg.QueryValueEx(key, exepath))
            filefound=False
    print(filefound)
    key.Close()
    reg.Close()

    ##If DPI Scaling was detected and program marked in registry, restart program. This will work in SHELL and your compiled EXE, not IDLE.

    if filefound==False:
        print('Restarting')
        python = sysex
        osexecl(python, python, * sysargv)
    else:
        YourApp().run()

来源:https://stackoverflow.com/questions/43401709/marking-your-python-program-as-high-dpi-aware-seamlessly-windows

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