Win32api is not giving the correct coordinates with GetCursorPos() in python

徘徊边缘 提交于 2019-11-26 14:39:52

问题


When using the win32api from pywin, I am getting incorrect values for the cursor position. My screen's resolution is 1920x1080, but when I use GetCursorPos() I have (0,0) in the top left and (1535,863) in the bottom right. The code I am using is as follows:

import win32api

def getCursor():
    print win32api.GetCursorPos()

I am trying this using python 2.7 on windows 10, but I was also getting this error in python 2.6 on windows 8. Is there any solution or workaround to this problem?


回答1:


You are subject to DPI virtualization. Your application has not declared itself aware of high DPI and you have a font scaling of 125%.

If you want to avoid DPI virtualization either add the high DPI aware option to the application manifest or call either SetProcessDPIAware or SetProcessDPIAwareness.




回答2:


You can set the awareness level like this:

import ctypes
awareness = ctypes.c_int()
ctypes.windll.shcore.SetProcessDpiAwareness(2)

The awareness levels are defined as follows:

typedef enum _PROCESS_DPI_AWARENESS { 
    PROCESS_DPI_UNAWARE = 0,
    /*  DPI unaware. This app does not scale for DPI changes and is
        always assumed to have a scale factor of 100% (96 DPI). It
        will be automatically scaled by the system on any other DPI
        setting. */

    PROCESS_SYSTEM_DPI_AWARE = 1,
    /*  System DPI aware. This app does not scale for DPI changes.
        It will query for the DPI once and use that value for the
        lifetime of the app. If the DPI changes, the app will not
        adjust to the new DPI value. It will be automatically scaled
        up or down by the system when the DPI changes from the system
        value. */

    PROCESS_PER_MONITOR_DPI_AWARE = 2
    /*  Per monitor DPI aware. This app checks for the DPI when it is
        created and adjusts the scale factor whenever the DPI changes.
        These applications are not automatically scaled by the system. */
} PROCESS_DPI_AWARENESS;

Check this answer: https://stackoverflow.com/a/44422362/8537759



来源:https://stackoverflow.com/questions/32541475/win32api-is-not-giving-the-correct-coordinates-with-getcursorpos-in-python

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